A field guide to Job hierarchies, why SupervisorJob exists, and the supervisorScope mistakes that quietly reintroduce the bug you were trying to fix.
Here is a snippet that has shipped in more Android codebases than anyone would like to admit:
viewModelScope.launch {
val eta = async { api.etaEstimate(orderId) } // throws IOException
try {
render(eta.await())
} catch (e: IOException) {
showFallbackEta() // you expect this to run
}
}
The author’s mental model is sensible: the failure belongs to the Deferred, await() rethrows it, and the catch handles it. Yet in production the screen shows no fallback, and in many setups the process dies with a stack trace that points at a line you thought was protected.
Why wrapping async in try/catch doesn't catch what you think it does: by the time await() reports anything, the failure has already been delivered to the parent through the Job tree. The try/catch sits on the observation path. The damage happens on the propagation path, and the two are independent.
The rest of this post builds the mental model that makes that sentence obvious, then walks through the failure modes that follow from it.
1. The parent/child Job tree and what "structured" means
Every coroutine builder (launch, async, withContext, coroutineScope, and friends) creates a new Job. That Job becomes a child of whatever Job it finds in the CoroutineContext it was started from. A CoroutineScope is little more than a context that carries a root Job.
“Structured” does not mean “tidy code”. It means the tree is a runtime fact that the library enforces:
- A child cannot outlive its parent.
- A parent cannot complete while a child is running.
- Cancellation and failure are signals that travel along the edges of that tree.
Everything in this post is a consequence of those edges. If you remember one thing, make it this: failure climbs the edges, cancellation descends them, and a parent’s completion waits on its children. A failure reaches a sibling by going up to the parent first, then coming back down as cancellation.
2. The three rules
-
A parent waits for its children. A
launchblock can return while its children are still running; the coroutine is not complete until they finish. That is whycoroutineScope { launch { … } }suspends until the innerlaunchis done. - Cancelling a parent cancels all of its children. Cancellation flows downward, and it is cooperative: each child stops at its next suspension point that checks for cancellation.
- A failing child cancels its parent. The parent then cancels the remaining children, which is exactly how a failure reaches siblings it has no direct link to.
One carve-out matters in practice. A CancellationException is how cancellation is represented, and it is treated as a normal way to end rather than as a failure. A child that is merely cancelled does not cancel its parent. Only a child that ends with a different throwable triggers rule 3.
3. Demo: two parallel calls, one failure kills the other
Imagine an order-tracking screen that needs the courier’s position and an ETA estimate. They are independent, so we run them in parallel.
import kotlinx.coroutines.*
import java.io.IOException
import kotlin.coroutines.cancellation.CancellationException
data class CourierPosition(val lat: Double, val lng: Double)
data class EtaEstimate(val minutes: Int)
data class TrackingState(val position: CourierPosition, val eta: EtaEstimate)
class TrackingApi {
suspend fun courierPosition(orderId: String): CourierPosition {
try {
delay(300) // slow but healthy
return CourierPosition(lat = 1.0, lng = 2.0)
} catch (e: CancellationException) {
println("courierPosition cancelled: ${e.message}")
throw e // always rethrow
}
}
suspend fun etaEstimate(orderId: String): EtaEstimate {
delay(120)
throw IOException("ETA service returned 503") // fast and broken
}
}
suspend fun loadTracking(api: TrackingApi, orderId: String): TrackingState = coroutineScope {
val position = async { api.courierPosition(orderId) }
val eta = async { api.etaEstimate(orderId) }
TrackingState(position.await(), eta.await())
}
fun main() = runBlocking {
runCatching { loadTracking(TrackingApi(), "order-42") }
.onFailure { println("loadTracking failed with: $it") }
}
Expected output (message text varies slightly between library versions):
courierPosition cancelled: Parent job is Cancelling
loadTracking failed with: java.io.IOException: ETA service returned 503
The position request had nothing wrong with it. It was cancelled at roughly the 120 ms mark, 180 ms before it would have finished, because its sibling failed.
This is the correct behavior for a block of work that is all-or-nothing. It is the wrong behavior for a dashboard where partial data is better than no data. The library cannot know which one you meant, so it picks the safe default: fail together.
4. SupervisorJob and supervisorScope: what they change and what they don't
A supervisor changes exactly one rule. A child’s failure is not propagated up to the supervisor and therefore does not cancel its other children.
There are two forms:
-
SupervisorJob()is theJobyou put at the root of a scope you build yourself. -
supervisorScope { }is the suspending block version: it behaves likecoroutineScope, but its direct children are supervised.
A supervisor-based version of our loader lets the ETA fail without taking the position down:
data class TrackingState(val position: CourierPosition, val eta: EtaEstimate?)
inline fun <T> runCatchingCancellable(block: () -> T): Result<T> =
try {
Result.success(block())
} catch (e: CancellationException) {
throw e // never swallow cancellation
} catch (e: Throwable) {
Result.failure(e)
}
suspend fun loadTracking(api: TrackingApi, orderId: String): TrackingState = supervisorScope {
val position = async { api.courierPosition(orderId) }
val eta = async { api.etaEstimate(orderId) }
TrackingState(
position = position.await(), // required
eta = runCatchingCancellable { eta.await() }.getOrNull(), // optional
)
}
A note on that helper: the standard library’s runCatching catches every Throwable, including CancellationException, so inside suspending code it can quietly swallow cancellation. The helper rethrows it, which is the behavior you want around suspend calls.
What a supervisor does not change
- It does not catch anything. A failure is still a failure; it just stops travelling upward. Someone still has to observe it.
- It does not stop downward cancellation. Cancel the supervisor and all children are cancelled.
- It does not make the parent finish early. The parent still waits for every child.
- It only supervises its direct children. A grandchild’s failure fails the child above it, and that child’s failure is what the supervisor sees.
The supervisorScope mistakes
These are the ones that survive code review because each looks like the fix.
Mistake A: expecting try/catch around supervisorScope to catch child failures.
try {
supervisorScope {
launch { syncContacts() } // throws IOException
launch { syncCalendar() }
}
} catch (e: IOException) {
// Never runs for failures inside those launch blocks.
}
A launch child under a supervisor has nobody above it to take the exception, so it goes to a CoroutineExceptionHandler in the context, and if none exists, to the thread's uncaught exception handler. On Android that means a crash. The catch only sees exceptions thrown by the supervisorScope body itself, such as a failing await() or a direct throw.
Mistake B: putting the supervisor at the wrong level.
coroutineScope {
launch { supervisorScope { fetchA() } } // does not protect fetchB
launch { fetchB() }
}
The supervisor only changes how it treats its own children. An exception thrown in the body of that inner supervisorScope still fails it and is rethrown to its parent, which cancels the sibling. To shield siblings from each other, the supervisor has to be their parent.
Mistake C: a supervised async that nobody awaits.
supervisorScope {
async { sendAnalyticsBatch() } // fails silently
}
An async child under a supervisor keeps its exception inside the Deferred. If nothing calls await(), the failure is never observed, never logged, and never crashes. Use launch for fire-and-forget work, and give it a handler.
Mistake D: using it as a blanket for every screen. If two calls genuinely depend on each other, failing together is the correct outcome. Reach for a supervisor when the product says partial results are acceptable, not when the stack trace is annoying.
5. launch vs async: when the exception surfaces
Both builders deliver a failure to a regular parent immediately. The difference is what else happens:
-
launchhas no result to hold the failure. If the parent doesn't take it, it goes to a handler or the thread's uncaught hook. There is nothing for you to wrap intry/catch, becauselaunchreturns aJobright away, long before the body finishes. -
asyncalso stores the failure in theDeferred, soawait()can rethrow it later.
Back to the hook. With a regular parent, eta fails and the parent coroutine becomes cancelling first. In the common case the await() call then throws a CancellationException, not your IOException, so the catch (e: IOException) branch is skipped. Even in a timing where it does run, the scope has already been told, and the failure continues up the tree.
Two fixes, with different semantics:
// Fix 1: isolate the failure behind a coroutineScope boundary.
val eta: EtaEstimate? = try {
coroutineScope { async { api.etaEstimate(orderId) }.await() }
} catch (e: IOException) {
null // coroutineScope rethrows the child's exception to *this* caller
}
// Fix 2: supervise, then catch at await().
supervisorScope {
val eta = async { api.etaEstimate(orderId) }
val value = try { eta.await() } catch (e: IOException) { null }
render(value)
}
coroutineScope rethrows a child's exception to its caller as an ordinary exception, so the boundary turns a propagating failure into a catchable one. That is the exact property the broken snippet lacked.
6. The trap: SupervisorJob() as a child's context element
This is the most common wrong turn after someone learns that supervisors exist:
// ANTI-PATTERN: shown to explain the bug. Do not copy this into real code.
viewModelScope.launch {
launch(SupervisorJob()) { refreshFeed() } // detached from viewModelScope
launch(SupervisorJob()) { refreshBadges() } // detached from viewModelScope
}
Snippets in this section marked ANTI-PATTERN are deliberately wrong. They are here so you can recognize them in code review, not so you can paste them.
It reads as “run these two under a supervisor”. It does something else. A Job is a context element, and a Job placed in the context passed to launch replaces the parent link that would have come from the enclosing scope. The new coroutine becomes a child of that fresh SupervisorJob(), which has no parent and never completes on its own.
You can observe the break directly:
fun main() = runBlocking {
val screenScope = CoroutineScope(Job() + Dispatchers.Default)
// Deliberately wrong, for demonstration only.
val detached = screenScope.launch(SupervisorJob()) {
delay(1_000)
println("still running after the scope was cancelled")
}
println("children of screenScope: ${screenScope.coroutineContext.job.children.count()}") // 0
screenScope.cancel()
delay(1_500)
println("detached cancelled? ${detached.isCancelled}") // false
}
The consequences are all bad and all quiet:
-
Lost cancellation. Leaving the screen cancels
viewModelScope, but this coroutine isn't in its tree, so it keeps running and holds references. -
Lost waiting. A parent that should wait for the work no longer does, so
coroutineScope-style guarantees evaporate. -
No sibling protection either. The outer
launchstill has a regularJob, so anything launched inside it still fails together:
// ANTI-PATTERN: the SupervisorJob() here does not supervise the inner launches.
scope.launch(SupervisorJob()) {
launch { throw IOException("boom") }
launch { awaitCancellation() } // cancelled anyway
}
The correct tools, depending on the situation:
// 1. Supervise a group of siblings you start right now.
viewModelScope.launch {
supervisorScope {
launch { refreshFeed() }
launch { refreshBadges() }
}
}
// 2. Build a long-lived scope that stays attached to an existing parent.
val childScope = CoroutineScope(SupervisorJob(parent = coroutineContext.job) + Dispatchers.Default)
// 3. Build a root scope once, with a SupervisorJob and nothing to attach to.
val appScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
The rule of thumb: a Job in a builder's context is a parent, not a policy. If you pass one, you are choosing a new parent.
7. CoroutineExceptionHandler: where it works and where it is ignored
A handler is a last resort for exceptions that nothing else will receive. It is consulted by the root of a coroutine tree, and it cannot recover: by the time it runs, the coroutine has already finished.
val handler = CoroutineExceptionHandler { _, e -> Log.e("Tracking", "Unhandled", e) }
// Runs: root coroutine, nobody else will see the exception.
scope.launch(handler) { throw IOException("a") }
// Ignored: the inner handler is on a child. The failure goes to the parent,
// which has no handler, so it ends up at the thread's uncaught hook.
scope.launch { launch(handler) { throw IOException("b") } }
// Ignored: async reports through await(), not through the handler.
scope.async(handler) { throw IOException("c") }
Practical guidance:
- Install it where the tree starts: on the scope’s context, so every root coroutine inherits it.
-
Inside
supervisorScope, a handler on the child (or inherited from the scope) does run, because supervised children have no failing parent to defer to. -
It never sees
CancellationException. Cancellation is not a failure. -
On Android,
viewModelScopehas no handler by default, so an uncaughtlaunchfailure crashes the app. Adding one converts crashes into log lines. Do that deliberately and report to your crash tool, or you will convert crashes into silent data bugs.
8. Choosing between viewModelScope, lifecycleScope, and a custom application scope
The question is not “which one is convenient”, it is “who owns this work, and when should it stop?”
-
viewModelScopeisSupervisorJob() + Dispatchers.Main.immediate, cancelled inonCleared(). Use it for loads and actions that exist to produce screen state. It survives configuration changes, which is the whole point. -
lifecycleScopeis tied to aLifecycleOwnerand is also supervised. Use it for UI-only work that should stop when the view goes away, and collect flows withrepeatOnLifecycleso collection pauses when the UI is not visible. - A custom application scope is for work whose result matters after the screen is gone: flushing an outbox, finishing an upload you already told the user succeeded.
class App : Application() {
val applicationScope = CoroutineScope(
SupervisorJob() +
Dispatchers.Default +
CoroutineName("application") +
CoroutineExceptionHandler { _, e -> CrashReporter.record(e) } // your reporting hook
)
}
class OutboxRepository(
private val api: OutboxApi,
private val appScope: CoroutineScope, // injected, easy to replace in tests
) {
fun sendInBackground(message: Message) {
appScope.launch { api.send(message) }
}
}
A few boundaries worth holding:
- Expose
suspendfunctions from repositories and let the caller's scope decide the lifetime. Take an application scope only for work that is meant to outlive callers. - Avoid
GlobalScope. The scope itself carries noJob, so everyGlobalScope.launchstarts an unattached top-level coroutine. You do get aJobhandle for that one coroutine, but nothing ties it to a lifecycle and there is no scope-wide cancel, so a stuck coroutine can live as long as the process. - An application scope outlives every screen, and so does anything captured by a closure launched in it. Don’t capture an
Activity,Fragment,View, orViewModelinsideappScope.launch { }; pass plain values instead. - A process can be killed at any time. If the work must survive that, no scope is enough; hand it to
WorkManager. - Inject the dispatcher too. Hard-coded
Dispatchers.IOinside a scope makes tests slow and non-deterministic.
A failure-mode checklist
- Wrapping
asyncintry/catchand expecting it to stop the parent from being cancelled. Put acoroutineScopeboundary inside thetry, or supervise. -
catch (e: Exception)around suspending code swallowingCancellationException, leaving a "cancelled" coroutine that keeps working. Rethrow it, or use a helper that does. -
kotlin.runCatchingaround suspend calls: it catchesCancellationExceptiontoo, for the same reason. Use a variant that rethrows it. -
try/catcharoundsupervisorScopeassuming it catcheslaunchfailures. - A supervisor placed inside the failing child instead of above the siblings.
- An un-awaited
asyncunder a supervisor, hiding a failure forever. -
launch(SupervisorJob())detaching work from its scope. - A
CoroutineExceptionHandlerattached to a child, or to anasync, where it is never consulted. - A scope chosen for convenience, not for ownership, producing either leaks or cancelled uploads.
🔚 Takeaways
Structured concurrency is not a style, it is a set of edges with rules attached. Failure climbs the edges, cancellation descends them, and a parent does not finish until its children do. SupervisorJob and supervisorScope turn off exactly one of those behaviors, failure climbing, and leave the others intact. Once you can draw the tree for the code in front of you, most of the surprising behavior stops being surprising.
📘 Master Your Next Technical Interview
Since Java is the foundation of Android development, mastering DSA is essential. I highly recommend “Mastering Data Structures & Algorithms in Java”. It’s a focused roadmap covering 100+ coding challenges to help you ace your technical rounds.
- E-book: Available on Google Play
- Kindle Edition: Available on Amazon
- Topmate: Available on Topmate
- Also available in Paperback & Hardcover.
Originally published on Medium.








Top comments (0)