Package kotlinx.coroutines

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

Types

CancellableContinuation

interface CancellableContinuation<in T> : Continuation<T>

Cancellable continuation. It is completed when it is resumed or cancelled. When cancel function is explicitly invoked, this continuation immediately resumes with CancellationException or with the specified cancel cause.

CompletableDeferred

interface CompletableDeferred<T> : Deferred<T>

A Deferred that can be completed via public functions complete or cancel.

CompletableJob

interface CompletableJob : Job

A job that can be completed using complete function. It is returned by Job() and SupervisorJob() constructor functions.

CopyableThrowable

interface CopyableThrowable<T> where T : Throwable, T : CopyableThrowable<T>

Throwable which can be cloned during stacktrace recovery in a class-specific way. For additional information about stacktrace recovery see STACKTRACE_RECOVERY_PROPERTY_NAME

CoroutineDispatcher

abstract class CoroutineDispatcher : ContinuationInterceptor

Base class that shall be extended by all coroutine dispatcher implementations.

CoroutineExceptionHandler

interface CoroutineExceptionHandler : Element

An optional element in the coroutine context to handle uncaught exceptions.

CoroutineName

data class CoroutineName : AbstractCoroutineContextElement

User-specified name of coroutine. This name is used in debugging mode. See newCoroutineContext for the description of coroutine debugging facilities.

CoroutineScope

interface CoroutineScope

Defines a scope for new coroutines. Every coroutine builder is an extension on CoroutineScope and inherits its coroutineContext to automatically propagate both context elements and cancellation.

CoroutineStart

enum class CoroutineStart

Defines start options for coroutines builders. It is used in start parameter of launch, async, and other coroutine builder functions.

Deferred

interface Deferred<out T> : Job

Deferred value is a non-blocking cancellable future — it is a Job with a result.

Dispatchers

expect object Dispatchers

Groups various implementations of CoroutineDispatcher.

DisposableHandle

interface DisposableHandle

A handle to an allocated object that can be disposed to make it eligible for garbage collection.

ExecutorCoroutineDispatcher

abstract class ExecutorCoroutineDispatcher : 
    CoroutineDispatcher,
    Closeable

CoroutineDispatcher that has underlying Executor for dispatching tasks. Instances of ExecutorCoroutineDispatcher should be closed by the owner of the dispatcher.

GlobalScope

object GlobalScope : CoroutineScope

A global CoroutineScope not bound to any job.

Job

interface Job : Element

A background job. Conceptually, a job is a cancellable thing with a life-cycle that culminates in its completion.

MainCoroutineDispatcher

abstract class MainCoroutineDispatcher : CoroutineDispatcher

Base class for special CoroutineDispatcher which is confined to application “Main” or “UI” thread and used for any UI-based activities. Instance of MainDispatcher can be obtained by Dispatchers.Main.

NonCancellable

object NonCancellable : Job

A non-cancelable job that is always active. It is designed for withContext function to prevent cancellation of code blocks that need to be executed without cancellation.

Runnable

expect interface Runnable

A runnable task for CoroutineDispatcher.dispatch.

ThreadContextElement

interface ThreadContextElement<S> : Element

Defines elements in CoroutineContext that are installed into thread context every time the coroutine with this element in the context is resumed on a thread.

Annotations

ExperimentalCoroutinesApi

annotation class ExperimentalCoroutinesApi

Marks declarations that are still experimental in coroutines API, which means that the design of the corresponding declarations has open issues which may (or may not) lead to their changes in the future. Roughly speaking, there is a chance that those declarations will be deprecated in the near future or the semantics of their behavior may change in some way that may break some code.

FlowPreview

annotation class FlowPreview

Marks Flow-related API as a feature preview.

InternalCoroutinesApi

annotation class InternalCoroutinesApi

Marks declarations that are internal in coroutines API, which means that should not be used outside of kotlinx.coroutines, because their signatures and semantics will change between future releases without any warnings and without providing any migration aids.

ObsoleteCoroutinesApi

annotation class ObsoleteCoroutinesApi

Marks declarations that are obsolete in coroutines API, which means that the design of the corresponding declarations has serious known flaws and they will be redesigned in the future. Roughly speaking, these declarations will be deprecated in the future but there is no replacement for them yet, so they cannot be deprecated right away.

Exceptions

CancellationException

open expect class CancellationException : 
    IllegalStateException

TimeoutCancellationException

class TimeoutCancellationException : CancellationException

This exception is thrown by withTimeout to indicate timeout.

Type Aliases

CompletionHandler

typealias CompletionHandler = (cause: Throwable?) -> Unit

Handler for Job.invokeOnCompletion and CancellableContinuation.invokeOnCancellation.

Extensions for External Classes

java.lang.ThreadLocal

java.util.concurrent.Executor

java.util.concurrent.ExecutorService

kotlin.Any

kotlin.collections.Collection

kotlin.coroutines.CoroutineContext

kotlin.js.Promise

org.w3c.dom.Window

Properties

DEBUG_PROPERTY_NAME

const val DEBUG_PROPERTY_NAME: String

Name of the property that controls coroutine debugging. See newCoroutineContext.

DEBUG_PROPERTY_VALUE_AUTO

const val DEBUG_PROPERTY_VALUE_AUTO: String

Automatic debug configuration value for DEBUG_PROPERTY_NAME. See newCoroutineContext.

DEBUG_PROPERTY_VALUE_OFF

const val DEBUG_PROPERTY_VALUE_OFF: String

Debug turned on value for DEBUG_PROPERTY_NAME. See newCoroutineContext.

DEBUG_PROPERTY_VALUE_ON

const val DEBUG_PROPERTY_VALUE_ON: String

Debug turned on value for DEBUG_PROPERTY_NAME. See newCoroutineContext.

IO_PARALLELISM_PROPERTY_NAME

const val IO_PARALLELISM_PROPERTY_NAME: String

Name of the property that defines the maximal number of threads that are used by Dispatchers.IO coroutines dispatcher.

isActive

val CoroutineScope.isActive: Boolean

Returns true when the current Job is still active (has not completed and was not cancelled yet).

Functions

CancellationException

expect fun CancellationException(
    message: String?,
    cause: Throwable?
): CancellationException

CompletableDeferred

fun <T> CompletableDeferred(
    parent: Job? = null
): CompletableDeferred<T>

Creates a CompletableDeferred in an active state. It is optionally a child of a parent job.

fun <T> CompletableDeferred(value: T): CompletableDeferred<T>

Creates an already completed CompletableDeferred with a given value.

CoroutineExceptionHandler

fun CoroutineExceptionHandler(
    handler: (CoroutineContext, Throwable) -> Unit
): CoroutineExceptionHandler

Creates a CoroutineExceptionHandler instance.

CoroutineScope

fun CoroutineScope(context: CoroutineContext): CoroutineScope

Creates a CoroutineScope that wraps the given coroutine context.

Job

fun Job(parent: Job? = null): CompletableJob

Creates a job object in an active state. A failure of any child of this job immediately causes this job to fail, too, and cancels the rest of its children.

MainScope

fun MainScope(): CoroutineScope

Creates the main CoroutineScope for UI components.

Runnable

expect fun Runnable(block: () -> Unit): Runnable

Creates Runnable task instance.

SupervisorJob

fun SupervisorJob(parent: Job? = null): CompletableJob

Creates a supervisor job object in an active state. Children of a supervisor job can fail independently of each other.

asPromise

fun <T> Deferred<T>.asPromise(): Promise<T>

Converts this deferred value to the instance of Promise.

async

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. 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.

awaitAll

suspend fun <T> awaitAll(
    vararg deferreds: Deferred<T>
): List<T>

Awaits for completion of given deferred values without blocking a thread and resumes normally with the list of values when all deferred computations are complete or resumes with the first thrown exception if any of computations complete exceptionally including cancellation.

cancel

fun CoroutineScope.cancel(
    cause: CancellationException? = null
): Unit

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.

cancelAndJoin

suspend fun Job.cancelAndJoin(): Unit

Cancels the job and suspends the invoking coroutine until the cancelled job is complete.

cancelChildren

fun Job.cancelChildren(
    cause: CancellationException? = null
): Unit

Cancels all children jobs of this coroutine using Job.cancel for all of them with an optional cancellation cause. Unlike Job.cancel on this job as a whole, the state of this job itself is not affected.

cancelFutureOnCancellation

fun CancellableContinuation<*>.cancelFutureOnCancellation(
    future: Future<*>
): Unit

Cancels a specified future when this job is cancelled. This is a shortcut for the following code with slightly more efficient implementation (one fewer object created).

coroutineScope

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

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.

delay

suspend fun delay(timeMillis: Long): Unit

Delays coroutine for a given time without blocking a thread and resumes it after a specified time. This suspending function is cancellable. If the Job of the current coroutine is cancelled or completed while this suspending function is waiting, this function immediately resumes with CancellationException.

ensureActive

fun CoroutineScope.ensureActive(): Unit

Ensures that current scope is active. Throws IllegalStateException if the context does not have a job in it.

fun Job.ensureActive(): Unit

Ensures that current job is active. If the job is no longer active, throws CancellationException. If the job was cancelled, thrown exception contains the original cancellation cause.

handleCoroutineException

fun handleCoroutineException(
    context: CoroutineContext,
    exception: Throwable
): Unit

Helper function for coroutine builder implementations to handle uncaught and unexpected exceptions in coroutines, that could not be otherwise handled in a normal way through structured concurrency, saving them to a future, and cannot be rethrown. This is a last resort handler to prevent lost exceptions.

invoke

operator suspend fun <T> CoroutineDispatcher.invoke(
    block: suspend CoroutineScope.() -> T
): T

Calls the specified suspending block with the given CoroutineDispatcher, suspends until it completes, and returns the result.

joinAll

suspend fun joinAll(vararg jobs: Job): Unit

Suspends current coroutine until all given jobs are complete. This method is semantically equivalent to joining all given jobs one by one with jobs.forEach { it.join() }.

launch

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. The coroutine is cancelled when the resulting job is cancelled.

newCoroutineContext

expect fun CoroutineScope.newCoroutineContext(
    context: CoroutineContext
): CoroutineContext

Creates context for the new coroutine. It installs Dispatchers.Default when no other dispatcher nor ContinuationInterceptor is specified, and adds optional support for debugging facilities (when turned on).

newFixedThreadPoolContext

fun newFixedThreadPoolContext(
    nThreads: Int,
    name: String
): ExecutorCoroutineDispatcher

Creates a coroutine execution context with the fixed-size thread-pool and built-in yield support. NOTE: The resulting ExecutorCoroutineDispatcher owns native resources (its threads).Resources are reclaimed by ExecutorCoroutineDispatcher.close.

newSingleThreadContext

fun newSingleThreadContext(
    name: String
): ExecutorCoroutineDispatcher

Creates a coroutine execution context using a single thread with built-in yield support. NOTE: The resulting ExecutorCoroutineDispatcher owns native resources (its thread).Resources are reclaimed by ExecutorCoroutineDispatcher.close.

plus

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.

promise

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.

runBlocking

fun <T> runBlocking(
    context: CoroutineContext = EmptyCoroutineContext,
    block: suspend CoroutineScope.() -> T
): T

Runs a new coroutine and blocks the current thread interruptibly until its completion. This function should not be used from a coroutine. It is designed to bridge regular blocking code to libraries that are written in suspending style, to be used in main functions and in tests.

supervisorScope

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

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

suspendCancellableCoroutine

suspend fun <T> suspendCancellableCoroutine(
    block: (CancellableContinuation<T>) -> Unit
): T

Suspends coroutine similar to suspendCoroutine, but provide an implementation of CancellableContinuation to the block. This function throws CancellationException if the coroutine is cancelled or completed while suspended.

withContext

suspend fun <T> withContext(
    context: CoroutineContext,
    block: suspend CoroutineScope.() -> T
): T

Calls the specified suspending block with a given coroutine context, suspends until it completes, and returns the result.

withTimeout

suspend fun <T> withTimeout(
    timeMillis: Long,
    block: suspend CoroutineScope.() -> T
): T

Runs a given suspending block of code inside a coroutine with a specified timeout and throws a TimeoutCancellationException if the timeout was exceeded.

withTimeoutOrNull

suspend fun <T> withTimeoutOrNull(
    timeMillis: Long,
    block: suspend CoroutineScope.() -> T
): T?

Runs a given suspending block of code inside a coroutine with a specified timeout and returns null if this timeout was exceeded.

yield

suspend fun yield(): Unit

Yields a thread (or thread pool) of the current coroutine dispatcher to other coroutines to run. If the coroutine dispatcher does not have its own thread pool (like Dispatchers.Unconfined) then this function does nothing, but checks if the coroutine Job was completed. This suspending function is cancellable. If the Job of the current coroutine is cancelled or completed when this suspending function is invoked or while this function is waiting for dispatching, it resumes with CancellationException.