Coroutine Cancellation in Kotlin
On this page (12sections)
Introduction
Coroutine Cancellation is a fundamental concept every Kotlin developer should understand. Advanced coroutine topics cover cancellation and channels for safe communication between concurrent tasks.
Coroutines can be cancelled cooperatively when they are no longer needed. In this tutorial you will learn the syntax, walk through a complete example program, study the sample output, and review best practices so you can apply the concept confidently in your own projects.
Definition
- Coroutines can be cancelled cooperatively when they are no longer needed.
- Cancellation throws CancellationException — handle cleanup in finally or use try/finally blocks.
- Long-running coroutines should call yield() or check for isActive to respect cancellation.
Syntax
val job = launch {
while (isActive) { delay(100L) }
}
job.cancel()
Coroutine Cancellation in Kotlin Example Program in Kotlin
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
var count = 0
while (isActive) {
delay(100L)
count++
}
println("This should not print")
}
delay(350L)
job.cancelAndJoin()
println("Coroutine cancelled after partial work")
}
Sample Output
Coroutine cancelled after partial work
When to use
Use cancellation when a screen closes or a request is aborted; use channels when coroutines must exchange a stream of values.
How it works
-
The program starts with a
mainfunction — the entry point that runs when you execute the file. -
Coroutines can be cancelled cooperatively when they are no longer needed.
-
Run the program in IntelliJ IDEA, Android Studio, or with the Kotlin command-line compiler (
kotlinc/kotlin). Compare your console output with the sample output shown below.
Best Practices
- Always use structured concurrency scopes so cancellation propagates correctly.
- Close channels when production is finished to avoid leaking coroutines.
- Prefer Flow over Channel for many reactive stream use cases.
Common Mistakes
- Skipping the example and only reading the definition — hands-on practice cements the concept.
- Copying syntax without understanding nullable vs non-nullable types or scope rules.
- Ignoring compiler warnings that often point to safer alternatives.
Key Points
- Coroutines can be cancelled cooperatively when they are no longer needed.
- Cancellation throws CancellationException — handle cleanup in finally or use try/finally blocks.
- Long-running coroutines should call yield() or check for isActive to respect cancellation.
- Test the example locally and verify the output matches the sample.
- Experiment by changing input values to see how behaviour changes.
Notes
- Add the
kotlinx-coroutines-coredependency when running coroutine examples outside Android or IntelliJ. - Semicolons at the end of statements are optional in Kotlin.