coroutineScope
Creates a CoroutineScope and calls the specified suspend block with this scope. The provided scope inherits its coroutineContext from the outer scope, but overrides the context's Job.
This function is designed for parallel decomposition of work. When any child coroutine in this scope fails, this scope fails and all the rest of the children are cancelled (for a different behavior see supervisorScope). This function returns as soon as the given block and all its children coroutines are completed. A usage example of a scope looks like this:
suspend fun showSomeData() = coroutineScope {
val data = async(Dispatchers.IO) { // <- extension on current scope
... load some UI data for the Main thread ...
}
withContext(Dispatchers.Main) {
doSomeWork()
val result = data.await()
display(result)
}
}The scope in this example has the following semantics:
showSomeDatareturns as soon as the data is loaded and displayed in the UI.If
doSomeWorkthrows an exception, then theasynctask is cancelled andshowSomeDatarethrows that exception.If the outer scope of
showSomeDatais cancelled, both startedasyncandwithContextblocks are cancelled.If the
asyncblock fails,withContextwill be cancelled.
The method may throw a CancellationException if the current job was cancelled externally or may throw a corresponding unhandled Throwable if there is any unhandled exception in this scope (for example, from a crashed coroutine that was started with launch in this scope).