Junior — Middle
How does the completion of a child coroutine affect the parent scope in asynchronous operations?
sobes.tech AI
Answer from AI
In Kotlin Coroutines, a child coroutine inherits the context of the parent coroutine, including its scope. If a child coroutine terminates with an error, by default, this error propagates upward and cancels the parent scope along with all its child coroutines. This ensures structured concurrency and prevents resource leaks.
If, however, the child coroutine completes successfully, it does not affect the parent scope — it continues to work.
Example:
val parentJob = CoroutineScope(Dispatchers.Default).launch {
val child = launch {
throw Exception("Error in child coroutine")
}
child.join()
}
The parentJob will also be canceled due to the error in the child.
To prevent the parent from being canceled due to errors in child coroutines, you can use SupervisorJob, which isolates errors in child coroutines.