coroutineScope

suspend fun <R> coroutineScope(
    block: suspend CoroutineScope.() -> R
): R
(source)

Creates new CoroutineScope and calls the specified suspend block with this scope. The provided scope inherits its coroutineContext from the outer scope, but overrides context’s Job.

This function is designed for a 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 given block and all its children coroutines are completed. Example of the scope usages looks like this:

suspend fun loadDataForUI() = coroutineScope {

  val data = async { // <- extension on current scope
     ... load some UI data ...
  }

  withContext(UI) {
    doSomeWork()
    val result = data.await()
    display(result)
  }
}

Semantics of the scope in this example:

  1. loadDataForUI returns as soon as data is loaded and UI is updated.
  2. If doSomeWork throws an exception, then async task is cancelled and loadDataForUI rethrows that exception.
  3. If outer scope of loadDataForUI is cancelled, both started async and withContext are cancelled.

Method may throw CancellationException if the current job was cancelled externally or may throw the 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).