Package kotlinx.coroutines

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

Types

CancellableContinuation
Link copied to clipboard
common
interface CancellableContinuation<in T> : Continuation<T>
Cancellable continuation.
CancellationException
Link copied to clipboard
open class CancellationException(message: String?) : IllegalStateException
typealias CancellationException = CancellationException
typealias CancellationException = CancellationException
typealias CancellationException = <ERROR CLASS>
CompletableDeferred
Link copied to clipboard
common
interface CompletableDeferred<T> : Deferred<T>
A Deferred that can be completed via public functions complete or cancel.
CompletableJob
Link copied to clipboard
common
interface CompletableJob : Job
A job that can be completed using complete() function.
CompletionHandler
Link copied to clipboard
common
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.

CopyableThrowable
Link copied to clipboard
common
interface CopyableThrowable<T : Throwable, CopyableThrowable<T>>
Throwable which can be cloned during stacktrace recovery in a class-specific way.
CoroutineDispatcher
Link copied to clipboard
common
Base class to be extended by all coroutine dispatcher implementations.
CoroutineExceptionHandler
Link copied to clipboard
common
interface CoroutineExceptionHandler : CoroutineContext.Element
An optional element in the coroutine context to handle uncaught exceptions.
CoroutineName
Link copied to clipboard
common
data class CoroutineName(name: String) : AbstractCoroutineContextElement
User-specified name of coroutine.
CoroutineScope
Link copied to clipboard
common
interface CoroutineScope
Defines a scope for new coroutines.
CoroutineStart
Link copied to clipboard
common
enum CoroutineStart : Enum<CoroutineStart>
Defines start options for coroutines builders.
Deferred
Link copied to clipboard
common
interface Deferred<out T> : Job
Deferred value is a non-blocking cancellable future &mdash; it is a Job with a result.
DelicateCoroutinesApi
Link copied to clipboard
common
annotation class DelicateCoroutinesApi
Marks declarations in the coroutines that are delicate &mdash; they have limited use-case and shall be used with care in general code.
Dispatchers
Link copied to clipboard
common
object Dispatchers
Groups various implementations of CoroutineDispatcher.
object Dispatchers
object Dispatchers
object Dispatchers
Groups various implementations of CoroutineDispatcher.
DisposableHandle
Link copied to clipboard
common
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.
ExperimentalCoroutinesApi
Link copied to clipboard
common
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.
FlowPreview
Link copied to clipboard
common
Marks Flow-related API as a feature preview.
GlobalScope
Link copied to clipboard
common
object GlobalScope : CoroutineScope
A global CoroutineScope not bound to any job.
InternalCoroutinesApi
Link copied to clipboard
common
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
common
interface Job : CoroutineContext.Element
A background job.
MainCoroutineDispatcher
Link copied to clipboard
common
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.
NonCancellable
Link copied to clipboard
common
object NonCancellable : AbstractCoroutineContextElement, Job
A non-cancelable job that is always active.
ObsoleteCoroutinesApi
Link copied to clipboard
common
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.
Runnable
Link copied to clipboard
common
interface Runnable
A runnable task for CoroutineDispatcher.dispatch.
js
interface Runnable
A runnable task for CoroutineDispatcher.dispatch.
native
interface Runnable
A runnable task for CoroutineDispatcher.dispatch.
typealias Runnable = Runnable
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
common
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>
asCoroutineDispatcher
Link copied to clipboard
@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.
js
fun Window.asCoroutineDispatcher(): CoroutineDispatcher
Converts an instance of Window to an implementation of CoroutineDispatcher.
asDeferred
Link copied to clipboard
js
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
js
fun <T> Deferred<T>.asPromise(): Promise<T>
Converts this deferred value to the instance of Promise.
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.
await
Link copied to clipboard
js
suspend fun <T> Promise<T>.await(): T
Awaits for completion of the promise without blocking.
awaitAll
Link copied to clipboard
common
suspend fun <T> Collection<Deferred<T>>.awaitAll(): 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.
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
js
suspend fun Window.awaitAnimationFrame(): Double
Suspends coroutine until next JS animation frame and returns frame time on resumption.
awaitCancellation
Link copied to clipboard
common
suspend fun awaitCancellation(): Nothing
Suspends until cancellation, in which case it will throw a CancellationException.
cancel
Link copied to clipboard
common
fun CoroutineContext.cancel(cause: CancellationException? = null)
Cancels Job of this context with an optional cancellation cause.
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.
fun Job.cancel(message: String, cause: Throwable? = null)
Cancels current job, including all its children with a specified diagnostic error message.
cancelAndJoin
Link copied to clipboard
common
suspend fun Job.cancelAndJoin()
Cancels the job and suspends the invoking coroutine until the cancelled job is complete.
cancelChildren
Link copied to clipboard
common
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.
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.
cancelFutureOnCancellation
Link copied to clipboard
fun CancellableContinuation<*>.cancelFutureOnCancellation(future: Future<*>)
Cancels a specified future when this job is cancelled.
CancellationException
Link copied to clipboard
common
fun CancellationException(message: String?, cause: Throwable?): CancellationException
fun CancellationException(message: String?, cause: Throwable?): CancellationException
Creates a cancellation exception with a specified message and cause.
CompletableDeferred
Link copied to clipboard
common
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.
completeWith
Link copied to clipboard
common
fun <T> CompletableDeferred<T>.completeWith(result: Result<T>): Boolean
Completes this deferred value with the value or exception in the given result.
CoroutineExceptionHandler
Link copied to clipboard
common
inline fun CoroutineExceptionHandler(crossinline handler: (CoroutineContext, Throwable) -> Unit): CoroutineExceptionHandler
Creates a CoroutineExceptionHandler instance.
CoroutineScope
Link copied to clipboard
common
suspend fun <R> coroutineScope(block: suspend CoroutineScope.() -> R): R
Creates a CoroutineScope and calls the specified suspend block with this scope.
currentCoroutineContext
Link copied to clipboard
common
inline suspend fun currentCoroutineContext(): CoroutineContext
Returns the current CoroutineContext retrieved by using kotlin.coroutines.coroutineContext.
delay
Link copied to clipboard
common
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
common
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.
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.
handleCoroutineException
Link copied to clipboard
common
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.
invoke
Link copied to clipboard
common
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.
Job
Link copied to clipboard
common
fun Job(parent: Job? = null): CompletableJob
Creates a job object in an active state.
joinAll
Link copied to clipboard
common
suspend fun Collection<Job>.joinAll()
Suspends current coroutine until all given jobs are complete.
suspend fun joinAll(vararg jobs: Job)
Suspends current coroutine until all given jobs are complete.
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.
MainScope
Link copied to clipboard
common
fun MainScope(): CoroutineScope
Creates the main CoroutineScope for UI components.
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.
newFixedThreadPoolContext
Link copied to clipboard
fun newFixedThreadPoolContext(nThreads: Int, name: String): ExecutorCoroutineDispatcher
Creates a coroutine execution context with the fixed-size thread-pool and built-in yield support.
newSingleThreadContext
Link copied to clipboard
Creates a coroutine execution context using a single thread with built-in yield support.
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.
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.
runBlocking
Link copied to clipboard
native
fun <T> runBlocking(context: <ERROR CLASS> = EmptyCoroutineContext, block: suspend CoroutineScope.() -> T): T
Runs new coroutine and blocks current thread interruptibly until its completion.
fun <T> runBlocking(context: CoroutineContext = EmptyCoroutineContext, block: suspend CoroutineScope.() -> T): T
Runs a new coroutine and blocks the current thread interruptibly until its completion.
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.
Runnable
Link copied to clipboard
common
inline fun Runnable(crossinline block: () -> Unit): Runnable
Creates Runnable task instance.
js
inline fun Runnable(crossinline block: () -> Unit): Runnable
Creates Runnable task instance.
inline fun Runnable(crossinline block: () -> Unit): Runnable
Creates Runnable task instance.
native
inline fun Runnable(crossinline block: () -> Unit): Runnable
Creates Runnable task instance.
SupervisorJob
Link copied to clipboard
common
fun SupervisorJob(parent: Job? = null): CompletableJob
Creates a supervisor job object in an active state.
supervisorScope
Link copied to clipboard
common
suspend fun <R> supervisorScope(block: suspend CoroutineScope.() -> R): R
Creates a CoroutineScope with SupervisorJob and calls the specified suspend block with this scope.
suspendCancellableCoroutine
Link copied to clipboard
common
inline suspend fun <T> suspendCancellableCoroutine(crossinline block: (CancellableContinuation<T>) -> Unit): T
Suspends the coroutine like suspendCoroutine, but providing a CancellableContinuation to the block.
withContext
Link copied to clipboard
common
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
common
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
common
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
common
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
common
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
common
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
common
val CoroutineContext.job: Job
Retrieves the current Job instance from the given CoroutineContext or throws IllegalStateException if no job is present in the context.