CoroutineScope

interface 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, etc) and every scoping function (like coroutineScope, withContext, etc) 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 children coroutines. The corresponding instance of CoroutineScope shall be created with either CoroutineScope() or MainScope() functions. The difference between them is only in the CoroutineDispatcher:

The key part of custom usage of CustomScope is cancelling it and 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
}
}

Properties

coroutineContext
Link copied to clipboard
common
abstract val coroutineContext: CoroutineContext
The context of this scope.

Inheritors

GlobalScope
Link copied to clipboard
ProducerScope
Link copied to clipboard
ActorScope
Link copied to clipboard

Extensions

actor
Link copied to clipboard
fun <E> CoroutineScope.actor(context: CoroutineContext = EmptyCoroutineContext, capacity: Int = 0, start: CoroutineStart = CoroutineStart.DEFAULT, onCompletion: CompletionHandler? = null, block: suspend ActorScope<E>.() -> Unit): SendChannel<E>
Launches new coroutine that is receiving messages from its mailbox channel and returns a reference to its mailbox channel as a SendChannel.
async
Link copied to clipboard
common
fun <T> CoroutineScope.async(context: CoroutineContext = EmptyCoroutineContext, start: CoroutineStart = CoroutineStart.DEFAULT, block: suspend CoroutineScope.() -> T): Deferred<T>
Creates a coroutine and returns its future result as an implementation of Deferred.
broadcast
Link copied to clipboard
common
fun <E> CoroutineScope.broadcast(context: CoroutineContext = EmptyCoroutineContext, capacity: Int = 1, start: CoroutineStart = CoroutineStart.LAZY, onCompletion: CompletionHandler? = null, block: suspend ProducerScope<E>.() -> Unit): BroadcastChannel<E>
Launches new coroutine to produce a stream of values by sending them to a broadcast channel and returns a reference to the coroutine as a BroadcastChannel.
cancel
Link copied to clipboard
common
fun CoroutineScope.cancel(cause: CancellationException? = null)
Cancels this scope, including its job and all its children with an optional cancellation cause.
fun CoroutineScope.cancel(message: String, cause: Throwable? = null)
Cancels this scope, including its job and all its children with a specified diagnostic error message.
ensureActive
Link copied to clipboard
common
fun CoroutineScope.ensureActive()
Ensures that current scope is active.
isActive
Link copied to clipboard
common
val CoroutineScope.isActive: Boolean
Returns true when the current Job is still active (has not completed and was not cancelled yet).
launch
Link copied to clipboard
common
fun CoroutineScope.launch(context: CoroutineContext = EmptyCoroutineContext, start: CoroutineStart = CoroutineStart.DEFAULT, block: suspend CoroutineScope.() -> Unit): Job
Launches a new coroutine without blocking the current thread and returns a reference to the coroutine as a Job.
newCoroutineContext
Link copied to clipboard
common
fun CoroutineScope.newCoroutineContext(context: CoroutineContext): CoroutineContext
Creates a context for the new coroutine.
js
fun CoroutineScope.newCoroutineContext(context: CoroutineContext): CoroutineContext
Creates context for the new coroutine.
plus
Link copied to clipboard
common
operator fun CoroutineScope.plus(context: CoroutineContext): CoroutineScope
Adds the specified coroutine context to this scope, overriding existing elements in the current scope's context with the corresponding keys.
produce
Link copied to clipboard
common
fun <E> CoroutineScope.produce(context: CoroutineContext = EmptyCoroutineContext, capacity: Int = 0, block: suspend ProducerScope<E>.() -> Unit): ReceiveChannel<E>
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.
promise
Link copied to clipboard
js
fun <T> CoroutineScope.promise(context: CoroutineContext = EmptyCoroutineContext, start: CoroutineStart = CoroutineStart.DEFAULT, block: suspend CoroutineScope.() -> T): Promise<T>
Starts new coroutine and returns its result as an implementation of Promise.

Sources

common source
Link copied to clipboard