Kotlin/포스팅

코루틴 취소

짜집퍼박사(짜박) 2024. 1. 9. 18:05

코루틴의 취소는 비동기 작업을 중단하고 관련된 리소스를 해제하는 중요한 측면입니다. 코루틴은 취소될 때 예외가 발생하며, 이 예외를 통해 취소 이유 등을 처리할 수 있습니다. 코루틴을 취소하는 방법과 취소와 관련된 주요 개념에 대해 알아보겠습니다.

 

1. 코루틴 취소하기

cancel 함수

Job 인터페이스를 구현한 객체는 cancel 함수를 사용하여 취소될 수 있습니다. 이 함수를 호출하면 예외가 발생하고, 취소된 코루틴은 더 이상 실행되지 않습니다.

import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch {
        try {
            // 비동기 작업
            delay(1000)
            println("Coroutine is running.")
        } catch (e: CancellationException) {
            println("Coroutine is cancelled: ${e.message}")
        }
    }

    delay(500)
    job.cancel() // 코루틴을 취소하고 예외 발생
    job.join() // 코루틴이 완료될 때까지 대기

    println("End")
}

yield 함수 활용

yield 함수를 사용하여 현재 코루틴의 실행을 일시 중단하고 다른 코루틴에 양보함으로써 취소를 허용할 수 있습니다.

import kotlinx.coroutines.*

suspend fun mySuspendingFunction() {
    yield() // 다른 코루틴에 양보
    println("After yielding.")
}

fun main() = runBlocking {
    val job = launch {
        mySuspendingFunction()
    }

    delay(500)
    job.cancel() // 코루틴을 취소하고 예외 발생
    job.join() // 코루틴이 완료될 때까지 대기

    println("End")
}

 

2. 취소 예외 처리

취소된 코루틴은 CancellationException 예외를 던집니다. 이 예외를 잡아서 취소된 코루틴에 특별한 동작을 추가할 수 있습니다.

import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch {
        try {
            // 비동기 작업
            delay(1000)
            println("Coroutine is running.")
        } catch (e: CancellationException) {
            println("Coroutine is cancelled: ${e.message}")
        }
    }

    delay(500)
    job.cancel() // 코루틴을 취소하고 예외 발생
    job.join() // 코루틴이 완료될 때까지 대기

    println("End")
}

 

3. 취소 상태 확인

isActive 함수

isActive 함수를 사용하여 현재 코루틴이 활성화되어 있는지 확인할 수 있습니다.

import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch {
        // 비동기 작업
        delay(1000)
        println("Coroutine is running.")
    }

    delay(500)
    println("Job is active: ${job.isActive}")

    job.cancel()
    job.join()

    println("Job is active: ${job.isActive}")
    println("End")
}

 

4. 취소 이유와 상세 정보

getCancellationException 함수

getCancellationException 함수를 사용하여 취소 이유와 관련된 상세 정보를 확인할 수 있습니다.

import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch {
        try {
            // 비동기 작업
            delay(1000)
            println("Coroutine is running.")
        } catch (e: CancellationException) {
            val reason = e.getCancellationException()
            println("Cancellation reason: ${reason?.message}")
        }
    }

    delay(500)
    job.cancel("Custom cancellation reason") // 사용자 정의 이유로 코루틴을 취소
    job.join()

    println("End")
}

코루틴의 취소는 중요한 개념으로, 비동기 작업을 취소하고 코루틴 간 협력을 통해 작업을 중단할 수 있습니다. cancel 함수나 yield 함수를 통해 코루틴을 취소하고, 예외 처리를 통해 취소된 코루틴에서 추가적인 작업을 수행할 수 있습니다.

 

With ChatGPT

'Kotlin > 포스팅' 카테고리의 다른 글

코루틴 디스패치  (0) 2024.01.09
코루틴 타임아웃  (0) 2024.01.09
코루틴 잡 생명 주기  (0) 2024.01.09
코루틴 흐름 제어  (0) 2024.01.09
코루틴 문맥  (0) 2024.01.07