Middle+
What is the difference between coroutineScope and supervisorScope?
sobes.tech AI
Answer from AI
The main difference between coroutineScope and supervisorScope lies in exception handling.
- coroutineScope: Propagates cancellation to all its child coroutines. If one child coroutine completes with an exception,
coroutineScopecancels all other child coroutines and rethrows the exception. - supervisorScope: Does not propagate cancellation to its child coroutines. Exceptions in one child coroutine do not affect the execution of other child coroutines.
supervisorScopeitself does not handle exceptions; they must be handled inside the child coroutine (for example, usingtry-catch).
Illustration:
// coroutineScope:
// If exception1 occurs in coroutine1, coroutine2 will be canceled.
coroutineScope {
launch { /* coroutine1, may throw exception1 */ }
launch { /* coroutine2 */ }
}
// supervisorScope:
// If exception1 occurs in coroutine1, coroutine2 will continue execution.
supervisorScope {
launch { /* coroutine1, may throw exception1 */ }
launch { /* coroutine2 */ }
}
Thus, supervisorScope is useful when independent execution of child tasks is required, and failure of one should not affect others. coroutineScope is more suitable when all child tasks are logically connected as part of a single operation, and failure of any of them means the entire operation should be canceled.