liveBook · Manning

supervisorScope

As explained in Kotlin in Action, 2E

supervisorScope is a kotlinx.coroutines suspending function that creates a coroutine scope with supervisor semantics for its child coroutines.

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

How Kotlin in Action, 2E covers it

How deep it goes
Explains child-failure isolation, SupervisorJob semantics, cancellation, and exception routing without detailing handler implementation.
Examples
Demonstrates a repeating heartbeat alongside a sibling that throws UnsupportedOperationException after one second.
What it assumes
Assumes familiarity with coroutine scopes, child coroutines, launch, structured concurrency, and exception propagation.
What you can do after
Apply it via supervisorScope to prevent one child failure from cancelling sibling coroutines.
How it connects
Connects structured concurrency, SupervisorJob, coroutineScope, launch, and CoroutineExceptionHandler.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.