Package kotlinx.coroutines.experimental

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

Types

AbstractCoroutine

abstract class AbstractCoroutine<in T> : 
    JobSupport,
    Job,
    Continuation<T>,
    CoroutineScope

Abstract base class for implementation of coroutines in coroutine builders.

CancellableContinuation

interface CancellableContinuation<in T> : 
    Continuation<T>,
    Job

Cancellable continuation. Its job 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.

CommonPool

object CommonPool : CoroutineDispatcher

Represents common pool of shared threads as coroutine dispatcher for compute-intensive tasks.

CompletableDeferred

interface CompletableDeferred<T> : Deferred<T>

A Deferred that can be completed via public functions complete, completeExceptionally, and cancel.

CoroutineDispatcher

abstract class CoroutineDispatcher : 
    AbstractCoroutineContextElement,
    ContinuationInterceptor

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

CoroutineExceptionHandler

interface CoroutineExceptionHandler : Element

An optional element on 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

Receiver interface for generic coroutine builders, so that the code inside coroutine has a convenient access to its coroutineContext and its cancellation status via isActive.

CoroutineStart

enum class CoroutineStart

Defines start option 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.

Delay

interface Delay

This dispatcher feature is implemented by CoroutineDispatcher implementations that natively support scheduled execution of tasks.

DisposableHandle

interface DisposableHandle : Registration

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

EventLoop

interface EventLoop

Implemented by CoroutineDispatcher implementations that have event loop inside and can be asked to process next event from their event queue.

Job

interface Job : Element

A background job. Conceptually, a job is a cancellable thing with a simple life-cycle that culminates in its completion. Jobs can be arranged into parent-child hierarchies where cancellation or completion of parent immediately cancels all its children.

NonCancellable

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.

NonDisposableHandle

object NonDisposableHandle : DisposableHandle

No-op implementation of DisposableHandle.

Runnable

interface Runnable

A runnable task for CoroutineDispatcher.dispatch.

ThreadPoolDispatcher

class ThreadPoolDispatcher : 
    ExecutorCoroutineDispatcherBase,
    Closeable

Dispatches coroutine execution to a thread pool of a fixed size. Instances of this dispatcher are created with newSingleThreadContext and newFixedThreadPoolContext.

Unconfined

object Unconfined : CoroutineDispatcher

A coroutine dispatcher that is not confined to any specific thread. It executes initial continuation of the coroutine right here in the current call-frame and let the coroutine resume in whatever thread that is used by the corresponding suspending function, without mandating any specific threading policy.

Exceptions

CancellationException

open class CancellationException : IllegalStateException

CompletionHandlerException

class CompletionHandlerException : RuntimeException

This exception gets thrown if an exception is caught while processing CompletionHandler invocation for Job.

JobCancellationException

class JobCancellationException : CancellationException

Thrown by cancellable suspending functions if the Job of the coroutine is cancelled or completed without cause, or with a cause or exception that is not CancellationException (see Job.getCancellationException).

TimeoutCancellationException

class TimeoutCancellationException : TimeoutException

This exception is thrown by withTimeout to indicate timeout.

Type Aliases

CancellationException

typealias CancellationException = CancellationException

Thrown by cancellable suspending functions if the Job of the coroutine is cancelled while it is suspending.

CompletionHandler

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

Handler for Job.invokeOnCompletion.

Runnable

typealias Runnable = Runnable

A runnable task for CoroutineDispatcher.dispatch.

Extensions for External Classes

java.util.concurrent.Executor

kotlin.coroutines.experimental.CoroutineContext

kotlin.js.Promise

org.w3c.dom.Window

Properties

DefaultDispatcher

val DefaultDispatcher: CoroutineDispatcher

This is the default CoroutineDispatcher that is used by all standard builders like launch, async, etc if no dispatcher nor any other ContinuationInterceptor is specified in their context.

Functions

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 new CoroutineExceptionHandler instance.

EventLoop

fun EventLoop(
    thread: Thread = Thread.currentThread(),
    parentJob: Job? = null
): CoroutineDispatcher

Creates a new event loop that is bound the specified thread (current thread by default) and stops accepting new events when parentJob completes. Every continuation that is scheduled onto this event loop unparks the specified thread via LockSupport.unpark.

Job

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

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

asPromise

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

Converts this deferred value to the instance of Promise.

async

fun <T> async(
    context: CoroutineContext = DefaultDispatcher,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    parent: Job? = null,
    block: suspend CoroutineScope.() -> T
): Deferred<T>

Creates new coroutine and returns its future result as an implementation of Deferred.

cancelAndJoin

suspend fun Job.cancelAndJoin(): Unit

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

cancelChildren

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

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

cancelFutureOnCompletion

fun Job.cancelFutureOnCompletion(
    future: Future<*>
): DisposableHandle

Cancels a specified future when this job is complete.

delay

suspend fun delay(time: Int): Unit
suspend fun delay(
    time: Long,
    unit: TimeUnit = TimeUnit.MILLISECONDS
): 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.

disposeOnCompletion

fun Job.disposeOnCompletion(
    handle: DisposableHandle
): DisposableHandle

Disposes a specified handle when this job is complete.

handleCoroutineException

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

Helper function for coroutine builder implementations to handle uncaught exception in coroutines.

joinChildren

suspend fun Job.joinChildren(): Unit

Suspends coroutine until all children of this job are complete using Job.join for all of them. Unlike Job.join on this job as a whole, it does not wait until this job is complete.

launch

fun launch(
    context: CoroutineContext = DefaultDispatcher,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    parent: Job? = null,
    block: suspend CoroutineScope.() -> Unit
): Job

Launches new coroutine without blocking current thread and returns a reference to the coroutine as a Job. The coroutine is cancelled when the resulting job is cancelled.

newCoroutineContext

fun newCoroutineContext(
    context: CoroutineContext,
    parent: Job? = null
): CoroutineContext

Creates context for the new coroutine. It installs DefaultDispatcher 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
): ThreadPoolDispatcher

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

newSingleThreadContext

fun newSingleThreadContext(
    name: String
): ThreadPoolDispatcher

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

promise

fun <T> promise(
    context: CoroutineContext = DefaultDispatcher,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    parent: Job? = null,
    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 new coroutine and blocks current thread interruptibly until its completion. This function should not be used from 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.

suspendAtomicCancellableCoroutine

suspend fun <T> suspendAtomicCancellableCoroutine(
    holdCancellability: Boolean = false,
    block: (CancellableContinuation<T>) -> Unit
): T

Suspends coroutine similar to suspendCancellableCoroutine, but with atomic cancellation.

suspendCancellableCoroutine

suspend fun <T> suspendCancellableCoroutine(
    holdCancellability: Boolean = false,
    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,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend () -> 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(
    time: Int,
    block: suspend CoroutineScope.() -> T
): T
suspend fun <T> withTimeout(
    time: Long,
    unit: TimeUnit = TimeUnit.MILLISECONDS,
    block: suspend CoroutineScope.() -> T
): T

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

withTimeoutOrNull

suspend fun <T> withTimeoutOrNull(
    time: Int,
    block: suspend CoroutineScope.() -> T
): T?
suspend fun <T> withTimeoutOrNull(
    time: Long,
    unit: TimeUnit = TimeUnit.MILLISECONDS,
    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 Unconfined dispatcher) 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.