CoroutineScope
Defines a scope for new coroutines. Every coroutine builder (like launch, async, etc.) is an extension on CoroutineScope and inherits its coroutineContext to automatically propagate all its elements and cancellation.
The best ways to obtain a standalone instance of the scope are CoroutineScope() and MainScope() factory functions, taking care to cancel these coroutine scopes when they are no longer needed (see section on custom usage below for explanation and example).
Additional context elements can be appended to the scope using the plus operator.
Convention for structured concurrency
Manual implementation of this interface is not recommended, implementation by delegation should be preferred instead. By convention, the context of a scope should contain an instance of a job to enforce the discipline of structured concurrency with propagation of cancellation.
Every coroutine builder (like launch, async, and others) and every scoping function (like coroutineScope and withContext) provides its own scope with its own Job instance into the inner block of code it runs. By convention, they all wait for all the coroutines inside their block to complete before completing themselves, thus enforcing the structured concurrency. See Job documentation for more details.
Android usage
Android has first-party support for coroutine scope in all entities with the lifecycle. See the corresponding documentation.
Custom usage
CoroutineScope
should be declared as a property on entities with a well-defined lifecycle that are responsible for launching child coroutines. The corresponding instance of CoroutineScope
shall be created with either CoroutineScope()
or MainScope()
:
CoroutineScope()
uses the context provided to it as a parameter for its coroutines and adds a Job if one is not provided as part of the context.MainScope()
uses Dispatchers.Main for its coroutines and has a SupervisorJob.
The key part of custom usage of CoroutineScope
is cancelling it at the end of the lifecycle. The CoroutineScope.cancel extension function shall be used when the entity that was launching coroutines is no longer needed. It cancels all the coroutines that might still be running on behalf of it.
For example:
class MyUIClass {
val scope = MainScope() // the scope of MyUIClass, uses Dispatchers.Main
fun destroy() { // destroys an instance of MyUIClass
scope.cancel() // cancels all coroutines launched in this scope
// ... do the rest of cleanup here ...
}
/*
* Note: if this instance is destroyed or any of the launched coroutines
* in this method throws an exception, then all nested coroutines are cancelled.
*/
fun showSomeData() = scope.launch { // launched in the main thread
// ... here we can use suspending functions or coroutine builders with other dispatchers
draw(data) // draw in the main thread
}
}
Inheritors
Properties
The context of this scope. Context is encapsulated by the scope and used for implementation of coroutine builders that are extensions on the scope. Accessing this property in general code is not recommended for any purposes except accessing the Job instance for advanced usages.
Returns true
when the current Job is still active (has not completed and was not cancelled yet).
Functions
Launches new coroutine that is receiving messages from its mailbox channel and returns a reference to its mailbox channel as a SendChannel. The resulting object can be used to send messages to this coroutine.
Creates a coroutine and returns its future result as an implementation of Deferred. The running coroutine is cancelled when the resulting deferred is cancelled. The resulting coroutine has a key difference compared with similar primitives in other languages and frameworks: it cancels the parent job (or outer scope) on failure to enforce structured concurrency paradigm. To change that behaviour, supervising parent (SupervisorJob or supervisorScope) can be used.
Cancels this scope, including its job and all its children with an optional cancellation cause. A cause can be used to specify an error message or to provide other details on a cancellation reason for debugging purposes. Throws IllegalStateException if the scope does not have a job in it.
Cancels this scope, including its job and all its children with a specified diagnostic error message. A cause can be specified to provide additional details on a cancellation reason for debugging purposes. Throws IllegalStateException if the scope does not have a job in it.
Throws the CancellationException that was the scope's cancellation cause if the scope is no longer active.
Starts a new coroutine and returns its result as an implementation of CompletableFuture. The running coroutine is cancelled when the resulting future is cancelled or otherwise completed.
Creates a context for a new coroutine. It installs Dispatchers.Default when no other dispatcher or ContinuationInterceptor is specified and adds optional support for debugging facilities (when turned on) and copyable-thread-local facilities on JVM.
Creates a context for a new coroutine. It installs Dispatchers.Default when no other dispatcher or ContinuationInterceptor is specified and adds optional support for debugging facilities (when turned on) and copyable-thread-local facilities on JVM. See DEBUG_PROPERTY_NAME for description of debugging facilities on JVM.
Adds the specified coroutine context to this scope, overriding existing elements in the current scope's context with the corresponding keys.
Launches a new coroutine to produce a stream of values by sending them to a channel and returns a reference to the coroutine as a ReceiveChannel. This resulting object can be used to receive elements produced by this coroutine.
Starts new coroutine and returns its result as an implementation of Promise.
Starts new coroutine and returns its result as an implementation of Promise.