Sobes.tech
Junior — Middle

How is the cancellation of coroutines in asynchronous programming performed?

sobes.tech AI

Answer from AI

Cancellation of coroutines in Kotlin occurs through the Job mechanism. Each coroutine is launched with an associated Job object, which can be canceled by calling cancel(). When canceled, the coroutine receives a CancellationException, allowing it to terminate properly.

Key points:

  • To cancel, call job.cancel().
  • Inside the coroutine, you should periodically check for cancellation using isActive or use cancellable functions (e.g., delay(), yield()), which throw CancellationException.
  • If the coroutine does not handle cancellation, it may continue running, so it's important to write cancellable code.

Example:

val job = CoroutineScope(Dispatchers.Default).launch {
    repeat(1000) { i ->
        if (!isActive) return@launch  // check for cancellation
        println("Working $i")
        delay(500)  // cancellable function
    }
}

delay(1300)
job.cancel()  // cancel the coroutine
job.join()    // wait for completion
println("Coroutine canceled")

Thus, cancellation is cooperative: the coroutine must respond correctly to the cancellation signal.