Core primitives to work with coroutines.

Coroutine builder functions:

Name Result Scope Description
launch Job CoroutineScope Launches coroutine that does not have any result
async Deferred CoroutineScope Returns a single value with the future result
produce ReceiveChannel ProducerScope Produces a stream of elements
actor SendChannel ActorScope Processes a stream of messages
runBlocking T CoroutineScope Blocks the thread while the coroutine runs

Coroutine dispatchers implementing CoroutineDispatcher:

Name Description
DefaultDispatcher Is equal to CommonPool
CommonPool Confines coroutine execution to a shared pool of threads
newSingleThreadContext Create new single-threaded coroutine context
newFixedThreadPoolContext Creates new thread pool of a fixed size
Executor.asCoroutineDispatcher Extension to convert any executor
Unconfined Does not confine coroutine execution in any way

More context elements:

Name Description
NonCancellable A non-cancelable job that is always active
CoroutineExceptionHandler Handler for uncaught exception

Synchronization primitives for coroutines:

Name Suspending functions Description
Mutex lock Mutual exclusion
Channel send, receive Communication channel (aka queue or exchanger)

Top-level suspending functions:

Name Description
delay Non-blocking sleep
yield Yields thread in single-threaded dispatchers
withContext Switches to a different context
withTimeout Set execution time-limit with exception on timeout
withTimeoutOrNull Set execution time-limit will null result on timeout

Select expression waits for the result of multiple suspending functions simultaneously:

Receiver Suspending function Select clause Non-suspending version
Job join onJoin isCompleted
Deferred await onAwait isCompleted
SendChannel send onSend offer
ReceiveChannel receive onReceive poll
ReceiveChannel receiveOrNull onReceiveOrNull poll
Mutex lock onLock tryLock
none delay onTimeout none

Cancellation support for user-defined suspending functions is available with suspendCancellableCoroutine helper function. NonCancellable job object is provided to suppress cancellation with run(NonCancellable) {...} block of code.

This module provides debugging facilities for coroutines (run JVM with -ea or -Dkotlinx.coroutines.debug options) and newCoroutineContext function to write user-defined coroutine builders that work with these debugging facilities.

Packages

kotlinx.coroutines.experimental

General-purpose coroutine builders, contexts, and helper functions.

kotlinx.coroutines.experimental.channels

Channels – non-blocking primitives for communicating a stream of elements between coroutines.

kotlinx.coroutines.experimental.intrinsics

Low-level primitives for finer-grained control of coroutines.

kotlinx.coroutines.experimental.selects

Select expression to perform multiple suspending operations simultaneously until one of them succeeds.

kotlinx.coroutines.experimental.sync

Synchronization primitives (mutex).

Index

All Types