Sobes.tech
Junior — Middle

What are the differences between supervisorScope and coroutineScope in the context of coroutines?

sobes.tech AI

Answer from AI

coroutineScope and supervisorScope are constructs in Kotlin for managing the lifecycle of coroutines and error handling.

  • coroutineScope creates a new coroutine scope in which all child coroutines must complete before continuing. If one child coroutine fails, all others will also be canceled.

  • supervisorScope is similar to coroutineScope, but errors in child coroutines do not cancel other child coroutines. That is, if one coroutine fails, the others continue to run.

Example:

coroutineScope {
    launch { /* if it fails, it cancels all */ }
    launch { /* also cancels if another fails */ }
}

supervisorScope {
    launch { /* if it fails, others continue */ }
    launch { /* continues working despite errors in others */ }
}

Thus, supervisorScope is useful when you need to isolate errors of child coroutines, and coroutineScope when you want to cancel all upon any error.

What are the differences between supervisorScope and… - sobes.tech