NonCancellable Coroutines 사용해보기

2025. 4. 7. 00:15·Study/Kotlin
728x90
반응형

이전 글에서 코루틴을 취소하는 방법에 대해 설명해보았다.

 

여기서 생각해볼만한 것이 하나 있는데 바로 CancellationException을 사용해

코루틴을 종료시키기 직전 특정 작업을 하는 경우이다.

 

더 정확히 따지면 suspend function 호출이 필요하지만 불가능한 경우이다.

 

예제 코드와 같이 보자.

 

예제 코드

fun main() = runBlocking {
	val job = launch(Dispatcher.Default) {
    	repeat(10) { index ->
        	if (isActive) {
                println("repeat $index")
                Thread.sleep(100)
            } else {
            	println("something before cancel")
            	throw CancellationException()
            }
        }
    }
    
    delay(250)
    println("Cancel coroutine")
    job.cancel()
}

이 코드에서 else문 내부에서 suspend function을 통해 특정 작업을 하고 종료되었으면 하는 것이다.

 

하지만 구조상 isActive 프로퍼티가 false인 경우,

else문 내부로 진입하게 되고 여기서 suspend function을 호출하면 println 함수는 더이상 실행되지 않는다.

 

그렇다면 어떻게 suspend function을 사용할 수 있을까?

 

NonCancellable Job 사용하기

NonCancellable이라는 Job을 사용하면 취소된 코루틴에서 suspend function을 사용할 수 있다.

 

하지만 withContext를 사용해야만 한다.

 

그렇게 완성된 코드 일부는 이렇다.

if (isActive) {
	println("repeat $index")
	Thread.sleep(100)
} else {
	withContext(NonCancellable) {
		delay(100)
		println("something before cancel")
		throw CancellationException()
	}
}

 

참조

https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-non-cancellable/

 

NonCancellable

A non-cancelable job that is always active. It is designed for withContext function to prevent cancellation of code blocks that need to be executed without cancellation. Use it like this: withContext(NonCancellable) { // this code will not be cancelled} WA

kotlinlang.org

728x90
반응형
저작자표시 비영리 변경금지 (새창열림)

'Study > Kotlin' 카테고리의 다른 글

Exception Handling Using try-catch Clause in Coroutines  (0) 2025.05.06
Coroutines Cooperative Cancellation  (0) 2025.04.06
LifecycleScope 간단히 알아보기  (0) 2025.02.26
ViewModelScope 알아보기  (1) 2025.02.25
GlobalScope 알아보기  (0) 2025.02.17
'Study/Kotlin' 카테고리의 다른 글
  • Exception Handling Using try-catch Clause in Coroutines
  • Coroutines Cooperative Cancellation
  • LifecycleScope 간단히 알아보기
  • ViewModelScope 알아보기
BonusTrack02.dev
BonusTrack02.dev
공부, 일상
  • BonusTrack02.dev
    BonusTrack02.dev
    BonusTrack02.dev
  • 전체
    오늘
    어제
    • 분류 전체보기 (236)
      • Dev experience (85)
        • Android (84)
        • Kotlin (1)
      • Study (61)
        • Kotlin (25)
        • Swift (17)
        • Java (19)
      • 프로그래머스 (68)
      • 주저리주저리 (22)
        • 카페 (5)
        • 음식점 (4)
        • 컨퍼런스 (1)
        • 팝업스토어 (4)
        • 전시회 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    coroutines
    ios
    android
    PCCE
    CodeLab
    aac
    Observer
    room
    자바
    Material
    오블완
    viewModelScope
    프로그래머스
    ViewModel
    programmers
    databinding
    Java
    배열
    Kotlin
    jetpack
    getNumericValue
    스위프트
    LiveData
    티스토리챌린지
    코루틴
    코틀린
    daterangepicker
    SWIFT
    안드로이드
    MVVM
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
BonusTrack02.dev
NonCancellable Coroutines 사용해보기
상단으로

티스토리툴바