Cancellation Propagation in Coroutine Hierarchies
Understand how cancellation flows through parent-child coroutine relationships.
Cancellation Propagation in Coroutine Hierarchies is a free Kotlin Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Parent-Child Relationship
When a coroutine launches another with launch, the child joins the parent's Job. Cancelling the parent cancels all children.
import kotlinx.coroutines.*
fun main() = runBlocking {
val parent = launch {
launch { delay(1000); println("child 1") }
launch { delay(1000); println("child 2") }
delay(1000)
println("parent")
}
delay(50)
parent.cancel()
parent.join()
println("All cancelled")
}Child Failure Cancels Parent
If a child throws a non-cancellation exception, it cancels the parent and all siblings — this is the default Job behavior.
import kotlinx.coroutines.*
fun main() = runBlocking {
try {
coroutineScope {
launch {
delay(50)
throw RuntimeException("child failed")
}
launch {
delay(1000)
println("sibling — never prints")
}
}
} catch (e: RuntimeException) {
println("Caught: ${e.message}")
}
}Cancellation Does Not Propagate Upward
Cancellation of a child does NOT cancel the parent. Only unhandled exceptions do. A parent can cancel a child at will.
import kotlinx.coroutines.*
fun main() = runBlocking {
val parent = launch {
val child = launch {
delay(1000)
println("child done")
}
delay(50)
child.cancel() // cancels child
child.join()
println("parent still running") // parent is fine
}
parent.join()
}coroutineScope vs GlobalScope
coroutineScope creates a child scope: cancellation and errors propagate. GlobalScope creates orphan coroutines with no parent — avoid it in production.
import kotlinx.coroutines.*
fun main() = runBlocking {
try {
coroutineScope {
launch { delay(50); throw RuntimeException("error") }
}
} catch (e: Exception) {
println("coroutineScope propagated: ${e.message}")
}
// GlobalScope.launch { } would NOT propagate to runBlocking
}Cancelling a Subtree
Every launch or async returns a Job. Cancel a job to cancel its entire subtree including any nested launches.
import kotlinx.coroutines.*
fun main() = runBlocking {
val root = launch {
launch {
launch { delay(1000); println("deep") }
delay(1000)
}
}
delay(50)
root.cancel()
root.join()
println("Whole subtree cancelled")
}join() After cancel()
Always call join() after cancel() to wait for the coroutine and its children to fully stop before continuing.
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
try { delay(1000) }
finally { println("cleanup ran") }
}
delay(50)
job.cancel()
job.join() // waits for finally to complete
println("Proceeded after join")
}cancelAndJoin()
job.cancelAndJoin() is a convenience that cancels and then joins, equivalent to cancel() + join().
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
try { delay(1000) }
finally { println("cleanup") }
}
delay(50)
job.cancelAndJoin() // cancel + join in one call
println("Done")
}Propagation Through async
With async, exceptions are stored in the Deferred and thrown when you call await(). They still propagate to the parent if uncaught.
import kotlinx.coroutines.*
fun main() = runBlocking {
try {
coroutineScope {
val d = async { throw RuntimeException("async fail") }
d.await() // rethrows here
}
} catch (e: RuntimeException) {
println("Caught from async: ${e.message}")
}
}Structured Concurrency Guarantee
Structured concurrency guarantees that when a scope finishes, all its children have finished. No coroutine leaks — either they complete or they are cancelled.
import kotlinx.coroutines.*
suspend fun doWork() = coroutineScope {
launch { delay(100); println("work 1") }
launch { delay(200); println("work 2") }
// both children complete before doWork returns
}
fun main() = runBlocking {
doWork()
println("All work done")
}Cancellation Propagation Diagram
The hierarchy: parent cancel → all children cancelled. Child cancel → only that subtree. Child exception → parent cancelled → siblings cancelled.
import kotlinx.coroutines.*
fun main() = runBlocking {
// Parent
launch {
val c1 = launch { delay(1000); println("c1") } // child 1
val c2 = launch { delay(1000); println("c2") } // child 2
delay(50)
c1.cancel() // only c1 cancelled
c1.join()
println("c2 still active: ${c2.isActive}")
c2.cancelAndJoin()
}.join()
}CoroutineScope lifecycle in Android
In Android, viewModelScope is cancelled when the ViewModel is cleared. All launched coroutines are cancelled automatically — no manual cleanup needed.
import kotlinx.coroutines.*
// Pseudocode:
// class MyViewModel : ViewModel() {
// fun load() = viewModelScope.launch {
// val data = repo.fetch() // cancelled if VM cleared
// _state.value = data
// }
// }
fun main() = runBlocking { println("viewModelScope cancels on ViewModel.onCleared()") }Quick Check
What happens to sibling coroutines when a child throws an unhandled exception under a regular Job?
Recap
Parent cancellation cascades to all children. Child failure propagates up to the parent and siblings (with regular Job). Use cancelAndJoin() for clean teardown. Structured concurrency ensures no coroutine leaks.
Frequently asked questions
Is the “Cancellation Propagation in Coroutine Hierarchies” lesson free?
Yes — the full text of “Cancellation Propagation in Coroutine Hierarchies” is free to read here on the web, and the Kotlin Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Kotlin Academy course, upgrade to CoddyKit PRO.
What will I learn in “Cancellation Propagation in Coroutine Hierarchies”?
Understand how cancellation flows through parent-child coroutine relationships. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Kotlin Academy?
No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Cancellation Propagation in Coroutine Hierarchies” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Kotlin Academy lesson?
Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Cooperative Cancellation: isActive and ensureActive
- withTimeout and withTimeoutOrNull
- Cleanup with finally and NonCancellable
- Cancellation Propagation in Coroutine Hierarchies