0Pricing
Kotlin Academy · Lesson

Cooperative Cancellation: isActive and ensureActive

Make coroutines cancellable by checking isActive and calling ensureActive.

Why Cooperative Cancellation?

Kotlin coroutines use cooperative cancellation: a cancelled coroutine is only stopped when it cooperates by checking its cancellation state. A tight CPU loop will not stop until it checks.

import kotlinx.coroutines.*
fun main() = runBlocking {
    val job = launch {
        var i = 0
        while (true) { i++ } // never checks — never cancels!
    }
    delay(100)
    job.cancel()
    println("cancel sent but loop kept running until process ended")
}

Checking isActive

isActive is a property on CoroutineScope that returns false once cancellation is requested. Checking it in a loop makes the coroutine cooperate.

import kotlinx.coroutines.*
fun main() = runBlocking {
    val job = launch {
        var i = 0
        while (isActive) {
            i++
        }
        println("Loop exited after $i iterations")
    }
    delay(10)
    job.cancel()
    job.join()
}

All lessons in this course

  1. Cooperative Cancellation: isActive and ensureActive
  2. withTimeout and withTimeoutOrNull
  3. Cleanup with finally and NonCancellable
  4. Cancellation Propagation in Coroutine Hierarchies
← Back to Kotlin Academy