Functions Similar to coroutineScope
Learn about more functions that behave like coroutineScope.
We'll cover the following...
supervisorScope
The supervisorScope
function also behaves like coroutineScope
—it creates a CoroutineScope
that inherits from the outer scope and calls the specified suspend block. The difference is that it overrides the context’s Job
with SupervisorJob
, so it’s not canceled when a child raises an exception.
package kotlinx.coroutines.app import kotlinx.coroutines.* fun main() = runBlocking { println("Before") supervisorScope { launch { delay(1000) throw Error() } launch { delay(2000) println("Done") } } println("After") }
Using supervisorScope
We mainly use supervisorScope
in functions that start multiple independent tasks.
Press + to interact
suspend fun notifyAnalytics(actions: List<UserAction>) =supervisorScope {actions.forEach { action ->launch {notifyAnalytics(action)}}}
Silencing its exception propagation to the parent is not enough if we use async
. When we call await
, and the async
coroutine finishes with an exception, ...