Functions Similar to coroutineScope
Explore functions similar to coroutineScope in Kotlin such as supervisorScope which handles exceptions independently, withTimeout that limits execution time throwing exceptions on timeout, and withTimeoutOrNull which cancels without exceptions. Understand their use cases to manage coroutines effectively in your Android applications.
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")
}We mainly use supervisorScope in functions that start multiple independent tasks.
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, await will ...