Package kotlinx.coroutines

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

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

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

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

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

Types

CancellableContinuation
Link copied to clipboard
interface CancellableContinuation<in T> : Continuation<T>

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

CancellationException
Link copied to clipboard
expect open class CancellationException(message: String?) : IllegalStateException
actual typealias CancellationException = CancellationException
actual typealias CancellationException = CancellationException
actual typealias CancellationException = <ERROR CLASS>
CloseableCoroutineDispatcher
Link copied to clipboard
expect abstract class CloseableCoroutineDispatcher : CoroutineDispatcher

CoroutineDispatcher that provides a method to close it, causing the rejection of any new tasks and cleanup of all underlying resources associated with the current dispatcher. Examples of closeable dispatchers are dispatchers backed by java.lang.Executor and by kotlin.native.Worker.

actual abstract class CloseableCoroutineDispatcher : CoroutineDispatcher
actual typealias CloseableCoroutineDispatcher = ExecutorCoroutineDispatcher
actual abstract class CloseableCoroutineDispatcher : CoroutineDispatcher
CompletableDeferred
Link copied to clipboard
interface CompletableDeferred<T> : Deferred<T>

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

CompletableJob
Link copied to clipboard
interface CompletableJob : Job

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

CompletionHandler
Link copied to clipboard
typealias CompletionHandler = (cause: Throwable?) -> Unit

Handler for Job.invokeOnCompletion and CancellableContinuation.invokeOnCancellation.

Installed handler should not throw any exceptions. If it does, they will get caught, wrapped into CompletionHandlerException, and rethrown, potentially causing crash of unrelated code.

The meaning of cause that is passed to the handler:

  • Cause is null when the job has completed normally.

  • Cause is an instance of CancellationException when the job was cancelled normally. It should not be treated as an error. In particular, it should not be reported to error logs.

  • Otherwise, the job had failed.

Note: This type is a part of internal machinery that supports parent-child hierarchies and allows for implementation of suspending functions that wait on the Job's state. This type should not be used in general application code. Implementations of CompletionHandler must be fast and lock-free.

CopyableThreadContextElement
Link copied to clipboard

A ThreadContextElement copied whenever a child coroutine inherits a context containing it.

CopyableThrowable
Link copied to clipboard
interface CopyableThrowable<T : Throwable, 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
Link copied to clipboard

Base class to be extended by all coroutine dispatcher implementations.

CoroutineExceptionHandler
Link copied to clipboard
interface CoroutineExceptionHandler : CoroutineContext.Element

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

CoroutineName
Link copied to clipboard
data class CoroutineName(name: String) : AbstractCoroutineContextElement

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

CoroutineScope
Link copied to clipboard
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.

CoroutineStart
Link copied to clipboard
enum CoroutineStart : Enum<CoroutineStart>

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

Deferred
Link copied to clipboard
interface Deferred<out T> : Job

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

DelicateCoroutinesApi
Link copied to clipboard
annotation class DelicateCoroutinesApi

Marks declarations in the coroutines that are delicate — they have limited use-case and shall be used with care in general code. Any use of a delicate declaration has to be carefully reviewed to make sure it is properly used and does not create problems like memory and resource leaks. Carefully read documentation of any declaration marked as DelicateCoroutinesApi.

Dispatchers
Link copied to clipboard
expect object Dispatchers

Groups various implementations of CoroutineDispatcher.

actual object Dispatchers
actual object Dispatchers

Groups various implementations of CoroutineDispatcher.

actual object Dispatchers
DisposableHandle
Link copied to clipboard
fun interface DisposableHandle

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

ExecutorCoroutineDispatcher
Link copied to clipboard
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.

ExperimentalCoroutinesApi
Link copied to clipboard

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
Link copied to clipboard

Marks Flow-related API as a feature preview.

GlobalScope
Link copied to clipboard
object GlobalScope : CoroutineScope

A global CoroutineScope not bound to any job. Global scope is used to launch top-level coroutines which are operating on the whole application lifetime and are not cancelled prematurely.

InternalCoroutinesApi
Link copied to clipboard

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.

Job
Link copied to clipboard
interface Job : CoroutineContext.Element

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

MainCoroutineDispatcher
Link copied to clipboard
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
Link copied to clipboard
object NonCancellable : AbstractCoroutineContextElement, 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.

ObsoleteCoroutinesApi
Link copied to clipboard
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.

Runnable
Link copied to clipboard
expect interface Runnable

A runnable task for CoroutineDispatcher.dispatch.

actual interface Runnable

A runnable task for CoroutineDispatcher.dispatch.

actual typealias Runnable = Runnable
actual interface Runnable

A runnable task for CoroutineDispatcher.dispatch.

ThreadContextElement
Link copied to clipboard
interface ThreadContextElement<S> : CoroutineContext.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.

TimeoutCancellationException
Link copied to clipboard

This exception is thrown by withTimeout to indicate timeout.

Functions

asContextElement
Link copied to clipboard
fun <T> ThreadLocal<T>.asContextElement(value: T = get()): ThreadContextElement<T>

Wraps ThreadLocal into ThreadContextElement. The resulting ThreadContextElement maintains the given value of the given ThreadLocal for coroutine regardless of the actual thread its is resumed on. By default ThreadLocal.get is used as a value for the thread-local variable, but it can be overridden with value parameter. Beware that context element does not track modifications of the thread-local and accessing thread-local from coroutine without the corresponding context element returns undefined value. See the examples for a detailed description.

asCoroutineDispatcher
Link copied to clipboard
fun Window.asCoroutineDispatcher(): CoroutineDispatcher

Converts an instance of Window to an implementation of CoroutineDispatcher.

@JvmName(name = "from")
fun Executor.asCoroutineDispatcher(): CoroutineDispatcher

Converts an instance of Executor to an implementation of CoroutineDispatcher.

@JvmName(name = "from")
fun ExecutorService.asCoroutineDispatcher(): ExecutorCoroutineDispatcher

Converts an instance of ExecutorService to an implementation of ExecutorCoroutineDispatcher.

asDeferred
Link copied to clipboard
fun <T> Promise<T>.asDeferred(): Deferred<T>

Converts this promise value to the instance of Deferred.

asExecutor
Link copied to clipboard
fun CoroutineDispatcher.asExecutor(): Executor

Converts an instance of CoroutineDispatcher to an implementation of Executor.

asPromise
Link copied to clipboard
fun <T> Deferred<T>.asPromise(): Promise<T>

Converts this deferred value to the instance of Promise.

async
Link copied to clipboard
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.

await
Link copied to clipboard
suspend fun <T> Promise<T>.await(): T

Awaits for completion of the promise without blocking.

awaitAll
Link copied to clipboard
suspend fun <T> Collection<Deferred<T>>.awaitAll(): List<T>
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.

awaitAnimationFrame
Link copied to clipboard
suspend fun Window.awaitAnimationFrame(): Double

Suspends coroutine until next JS animation frame and returns frame time on resumption. The time is consistent with window.performance.now(). This function is cancellable. If the Job of the current coroutine is completed while this suspending function is waiting, this function immediately resumes with CancellationException.

awaitCancellation
Link copied to clipboard
suspend fun awaitCancellation(): Nothing

Suspends until cancellation, in which case it will throw a CancellationException.

cancel
Link copied to clipboard
fun CoroutineContext.cancel(cause: CancellationException? = null)

Cancels Job of this context with an optional cancellation cause. See Job.cancel for details.

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

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.

fun CoroutineScope.cancel(message: String, cause: Throwable? = null)

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.

fun Job.cancel(message: String, cause: Throwable? = null)

Cancels current job, including 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.

cancelAndJoin
Link copied to clipboard
suspend fun Job.cancelAndJoin()

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

cancelChildren
Link copied to clipboard
fun CoroutineContext.cancelChildren(cause: CancellationException? = null)

Cancels all children of the Job in this context, without touching the state of this job itself with an optional cancellation cause. See Job.cancel. It does not do anything if there is no job in the context or it has no children.

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

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
Link copied to clipboard
fun CancellableContinuation<*>.cancelFutureOnCancellation(future: Future<*>)

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

CancellationException
Link copied to clipboard
expect fun CancellationException(message: String?, cause: Throwable?): CancellationException
actual fun CancellationException(message: String?, cause: Throwable?): CancellationException

Creates a cancellation exception with a specified message and cause.

CompletableDeferred
Link copied to clipboard
fun <T> CompletableDeferred(value: T): CompletableDeferred<T>

Creates an already completedCompletableDeferred with a given value.

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

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

completeWith
Link copied to clipboard
fun <T> CompletableDeferred<T>.completeWith(result: Result<T>): Boolean

Completes this deferred value with the value or exception in the given result. Returns true if this deferred was completed as a result of this invocation and false otherwise (if it was already completed).

CoroutineExceptionHandler
Link copied to clipboard
inline fun CoroutineExceptionHandler(crossinline handler: (CoroutineContext, Throwable) -> Unit): CoroutineExceptionHandler

Creates a CoroutineExceptionHandler instance.

CoroutineScope
Link copied to clipboard
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.

currentCoroutineContext
Link copied to clipboard
inline suspend fun currentCoroutineContext(): CoroutineContext

Returns the current CoroutineContext retrieved by using kotlin.coroutines.coroutineContext. This function is an alias to avoid name clash with CoroutineScope.coroutineContext in a receiver position:

delay
Link copied to clipboard
suspend fun delay(timeMillis: Long)

Delays coroutine for a given time without blocking a thread and resumes it after a specified time.

suspend fun delay(duration: Duration)

Delays coroutine for a given duration without blocking a thread and resumes it after the specified time.

ensureActive
Link copied to clipboard
fun CoroutineContext.ensureActive()

Ensures that job in the current context is active.

fun CoroutineScope.ensureActive()

Ensures that current scope is active.

fun Job.ensureActive()

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.

ensurePresent
Link copied to clipboard
inline suspend fun ThreadLocal<*>.ensurePresent()

Checks whether current thread local is present in the coroutine context and throws IllegalStateException if it is not. It is a good practice to validate that thread local is present in the context, especially in large code-bases, to avoid stale thread-local values and to have a strict invariants.

handleCoroutineException
Link copied to clipboard
fun handleCoroutineException(context: CoroutineContext, exception: Throwable)

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
Link copied to clipboard
inline suspend operator fun <T> CoroutineDispatcher.invoke(noinline block: suspend CoroutineScope.() -> T): T

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

isPresent
Link copied to clipboard
inline suspend fun ThreadLocal<*>.isPresent(): Boolean

Return true when current thread local is present in the coroutine context, false otherwise. Thread local can be present in the context only if it was added via asContextElement to the context.

Job
Link copied to clipboard
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.

joinAll
Link copied to clipboard
suspend fun Collection<Job>.joinAll()

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

suspend fun joinAll(vararg jobs: Job)

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
Link copied to clipboard
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.

MainScope
Link copied to clipboard
fun MainScope(): CoroutineScope

Creates the main CoroutineScope for UI components.

newCoroutineContext
Link copied to clipboard
expect fun CoroutineScope.newCoroutineContext(context: CoroutineContext): CoroutineContext

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

actual 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
Link copied to clipboard
expect fun newFixedThreadPoolContext(nThreads: Int, name: String): CloseableCoroutineDispatcher
actual fun newFixedThreadPoolContext(nThreads: Int, name: String): CloseableCoroutineDispatcher

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.

actual fun newFixedThreadPoolContext(nThreads: Int, name: String): CloseableCoroutineDispatcher
newSingleThreadContext
Link copied to clipboard

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
Link copied to clipboard
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
Link copied to clipboard
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
Link copied to clipboard
expect fun <T> runBlocking(context: CoroutineContext = EmptyCoroutineContext, block: suspend CoroutineScope.() -> T): T

Runs a new coroutine and blocks the current thread 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.

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

runInterruptible
Link copied to clipboard
suspend fun <T> runInterruptible(context: CoroutineContext = EmptyCoroutineContext, block: () -> T): T

Calls the specified block with a given coroutine context in a interruptible manner. The blocking code block will be interrupted and this function will throw CancellationException if the coroutine is cancelled.

Runnable
Link copied to clipboard
expect inline fun Runnable(crossinline block: () -> Unit): Runnable

Creates Runnable task instance.

actual inline fun Runnable(crossinline block: () -> Unit): Runnable

Creates Runnable task instance.

actual inline fun Runnable(crossinline block: () -> Unit): Runnable

Creates Runnable task instance.

actual inline fun Runnable(crossinline block: () -> Unit): Runnable

Creates Runnable task instance.

SupervisorJob
Link copied to clipboard
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.

supervisorScope
Link copied to clipboard
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. This function returns as soon as the given block and all its child coroutines are completed.

suspendCancellableCoroutine
Link copied to clipboard
inline suspend fun <T> suspendCancellableCoroutine(crossinline block: (CancellableContinuation<T>) -> Unit): T

Suspends the coroutine like suspendCoroutine, but providing a CancellableContinuation to the block. This function throws a CancellationException if the Job of the coroutine is cancelled or completed while it is suspended.

withContext
Link copied to clipboard
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
Link copied to clipboard
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.

suspend fun <T> withTimeout(timeout: Duration, block: suspend CoroutineScope.() -> T): T

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

withTimeoutOrNull
Link copied to clipboard
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.

suspend fun <T> withTimeoutOrNull(timeout: Duration, block: suspend CoroutineScope.() -> T): T?

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

yield
Link copied to clipboard
suspend fun yield()

Yields the thread (or thread pool) of the current coroutine dispatcher to other coroutines on the same dispatcher to run if possible.

Properties

DEBUG_PROPERTY_NAME
Link copied to clipboard
const val DEBUG_PROPERTY_NAME: String

Name of the property that controls coroutine debugging.

DEBUG_PROPERTY_VALUE_AUTO
Link copied to clipboard
const val DEBUG_PROPERTY_VALUE_AUTO: String

Automatic debug configuration value for DEBUG_PROPERTY_NAME.

DEBUG_PROPERTY_VALUE_OFF
Link copied to clipboard
const val DEBUG_PROPERTY_VALUE_OFF: String

Debug turned on value for DEBUG_PROPERTY_NAME.

DEBUG_PROPERTY_VALUE_ON
Link copied to clipboard
const val DEBUG_PROPERTY_VALUE_ON: String

Debug turned on value for DEBUG_PROPERTY_NAME.

IO_PARALLELISM_PROPERTY_NAME
Link copied to clipboard
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
Link copied to clipboard
val CoroutineScope.isActive: Boolean

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

isActive
Link copied to clipboard
val CoroutineContext.isActive: Boolean

Returns true when the Job of the coroutine in this context is still active (has not completed and was not cancelled yet).

job
Link copied to clipboard
val CoroutineContext.job: Job

Retrieves the current Job instance from the given CoroutineContext or throws IllegalStateException if no job is present in the context.