이전 글에서 코루틴을 취소하는 방법에 대해 설명해보았다.
여기서 생각해볼만한 것이 하나 있는데 바로 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()
}
}
참조
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
'Language > Kotlin' 카테고리의 다른 글
Coroutines Cooperative Cancellation (0) | 2025.04.06 |
---|---|
LifecycleScope 간단히 알아보기 (0) | 2025.02.26 |
ViewModelScope 알아보기 (1) | 2025.02.25 |
GlobalScope 알아보기 (0) | 2025.02.17 |
Structured Concurrency in Coroutines (1) | 2025.01.19 |