supervisorScope is a suspending function that creates a structured-concurrency scope with supervisor semantics. When one child fails, sibling coroutines continue running, and the failure does not cancel the parent scope. section 18.2.3
Keep a heartbeat alive after a child fails
Wrap sibling launch calls in supervisorScope when one failing operation should not terminate another. In the example, a heartbeat repeats every 500 milliseconds while a second coroutine throws after one second. The heartbeat continues, although the exception remains visible through coroutine exception handling. section 18.2.3
Listing 18.4 Using a supervisor scope to stop the exception from propagating further
import kotlinx.coroutines.*
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
fun main(): Unit = runBlocking {
supervisorScope {
launch {
try {
while (true) {
println("Heartbeat!")
delay(500.milliseconds)
}
} catch (e: Exception) {
println("Heartbeat terminated: $e")
throw e
}
}
launch {
delay(1.seconds)
throw UnsupportedOperationException("Ow!")
}
}
}
Shows the compact Kotlin implementation with a heartbeat coroutine, a failing sibling, and supervisorScope around both launches. section 18.2.3
Use supervisorScope to preserve structured concurrency while changing child-failure behavior:
- Keep sibling coroutines running when one child throws. section 18.2.3
- Keep the parent and supervisor scope cancellable; supervision does not disable normal cancellation propagation. section 18.2.3
- Expect uncaught launch failures to reach a CoroutineExceptionHandler or the system-wide exception handler. section 18.6
