Sobes.tech
Junior — Middle

How does the termination of a child task affect the lifecycle of CoroutineScope?

sobes.tech AI

Answer from AI

In Kotlin Coroutines, the lifecycle of CoroutineScope depends on its child jobs as follows:

  • CoroutineScope manages a set of coroutines launched within its context.
  • If a child coroutine fails with an exception, it by default cancels the entire CoroutineScope and all its child coroutines.
  • If a child coroutine completes successfully, it does not affect the lifecycle of the CoroutineScope — it continues to run.

Thus, termination (cancellation or error) of a child task can lead to the cancellation of the entire CoroutineScope unless special error handling mechanisms are applied (e.g., SupervisorJob).

Example:

val scope = CoroutineScope(Job())

val child = scope.launch {
    // some work
    throw Exception("Error")
}

// After the child's error, scope and other child coroutines will be canceled

Using SupervisorJob allows isolating errors of child coroutines so they do not affect the entire scope.