Kotlin Coroutine Cancellation

A coroutine sometimes needs to stop before it finishes. A user leaves a screen, a download becomes unnecessary, or a request takes too long. Cancellation stops the work, frees resources, and saves battery and data.

A Note on the Door

Imagine a worker busy at a desk. A manager pins a note on the door that reads "Please stop". The note does not grab the worker by the arm. The worker stops after reading the note at the next checkpoint. Coroutine cancellation uses the same polite approach. The coroutine must check for the note.

 Coroutine work:  step 1 -- step 2 -- step 3 -- step 4
                              ^         ^
                         checkpoint  checkpoint
 cancel() called here --------+
 Coroutine sees the note at the checkpoint and stops

Cancelling a Job

The launch builder returns a Job. The cancel() function on that job posts the note.

import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch {
        repeat(10) { i ->
            println("Working $i")
            delay(300)
        }
    }
    delay(1000)
    println("Cancelling")
    job.cancelAndJoin()
    println("Stopped")
}

The program prints Working 0, Working 1, Working 2, and Working 3, then Cancelling and Stopped. The function cancelAndJoin() cancels the job and waits until it finishes.

Checkpoints Are Cooperative

Suspending functions such as delay and yield check for cancellation automatically. A tight calculation loop contains no such checkpoint, so it ignores the note.

val job = launch(Dispatchers.Default) {
    var i = 0
    while (i < 5) {          // never checks cancellation
        i++
    }
}

The property isActive adds a checkpoint. The function ensureActive() throws when the job is cancelled.

val job = launch(Dispatchers.Default) {
    var i = 0
    while (isActive) {
        i++
    }
    println("Loop ended cleanly")
}
delay(100)
job.cancelAndJoin()

What Happens Inside

Cancellation travels as a special exception named CancellationException. Normal try-catch blocks can catch it. Re-throw it, or the coroutine fails to stop.

try {
    delay(1000)
} catch (e: CancellationException) {
    println("Cancelled")
    throw e
}

Cleaning Up with finally

A finally block runs even after cancellation. Use it to close files and connections.

val job = launch {
    try {
        repeat(5) {
            println("Downloading $it")
            delay(400)
        }
    } finally {
        println("Closing connection")
    }
}
delay(900)
job.cancelAndJoin()

Suspending calls inside finally fail, because the job is already cancelled. Wrap them in withContext(NonCancellable) when cleanup needs to suspend.

finally {
    withContext(NonCancellable) {
        delay(100)
        println("Saved progress")
    }
}

Timeouts

A timeout cancels a coroutine automatically after a set time.

import kotlinx.coroutines.*

fun main() = runBlocking {
    try {
        withTimeout(1000) {
            repeat(5) {
                println("Waiting $it")
                delay(400)
            }
        }
    } catch (e: TimeoutCancellationException) {
        println("Too slow")
    }

    val result = withTimeoutOrNull(500) {
        delay(1000)
        "Done"
    }
    println(result)   // null
}

The function withTimeout throws an exception. The function withTimeoutOrNull returns null and keeps the code simpler.

Parent and Child Jobs

Cancelling a parent cancels every child.

 Parent job
   +-- Child A   (cancelled)
   +-- Child B   (cancelled)
   +-- Child C   (cancelled)

A failure in one child cancels siblings too, unless a supervisor job manages the group.

Quick Reference

ToolPurpose
job.cancel()Posts the stop request
job.cancelAndJoin()Stops and waits
isActiveCheckpoint inside loops
ensureActive()Throws when cancelled
withTimeout()Cancels after a time limit
NonCancellableProtects cleanup code