SupervisorJob
- Kotlin course
- Advanced
- Lesson 4/83
- 5 min
Learn error isolation with SupervisorJob.
What is SupervisorJob?
SupervisorJob is a special Job type that does not spread child coroutine failures to siblings. A normal Job cancels all siblings when one child fails; SupervisorJob keeps the failure local to that child.
This is useful when one request failing should not stop the others. With supervisorScope { ... } you open a supervisor scope and put several launch calls inside. If one child crashes, the others keep running.
Practice Two launches with supervisorScope
Inside runBlocking, open a supervisorScope. Write val job = launch { println("Inside") }, then wait with job.join(). After the scope, print println("Outside").
Starter code
// Two launches with supervisorScope
// write here
fun main() = runBlocking {
}Sample solution
fun main() = runBlocking {
supervisorScope {
val job = launch {
println("Inside")
}
job.join()
}
println("Outside")
}Expected output
Inside Outside
Using supervisorScope
supervisorScope is a suspending function; it creates a child scope with a fresh SupervisorJob and waits for all children. Even if one child fails, the others are not cancelled.
Example: supervisorScope { launch { fetchA() }; launch { fetchB() } }. If fetchA fails, fetchB still completes. This is useful for parallel independent work, such as several API calls running at once.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does SupervisorJob provide?
- Cancels all children
- Runs faster
- Increases thread count
- Isolates child failures Correct answer
Explanation: SupervisorJob keeps one child's failure from spreading to others.
2 Complete the supervisor scope name
supervisor____ {
launch { fetchA() }
launch { fetchB() }
}
supervisorScope {
launch { fetchA() }
launch { fetchB() }
}
Explanation: supervisorScope opens a supervisor scope.
3 Match SupervisorJob parts
| Term | Meaning |
|---|---|
SupervisorJob |
Isolates failures |
supervisorScope |
Supervisor scope |
Job |
Propagates errors |
launch |
Starts a child |