Deferred

interface Deferred<out T> : Job (source)

Deferred value is a non-blocking cancellable future.

It is created with async coroutine builder or via constructor of CompletableDeferred class. It is in active state while the value is being computed.

Deferred value has the following states:

State isActive isCompleted isCompletedExceptionally isCancelled
New (optional initial state) false false false false
Active (default initial state) true false false false
Completing (optional transient state) true false false false
Cancelling (optional transient state) false false false true
Cancelled (final state) false true true true
Resolved (final state) false true false false
Failed (final state) false true true false

Usually, a deferred value is created in active state (it is created and started). However, async coroutine builder has an optional start parameter that creates a deferred value in new state when this parameter is set to CoroutineStart.LAZY. Such a deferred can be be made active by invoking start, join, or await.

A deferred can be cancelled at any time with cancel function that forces it to transition to cancelling state immediately. Deferred that is not backed by a coroutine (see CompletableDeferred) and does not have children becomes cancelled on cancel immediately. Otherwise, deferred becomes cancelled when it finishes executing its code and when all its children complete.

                                                       wait children
      +-----+       start      +--------+   complete  +-------------+ finish +-----------+
      | New | ---------------> | Active | ----------> | Completing  | ---+-> | Resolved  |
      +-----+                  +--------+             +-------------+    |   |(completed)|
         |                         |                        |            |   +-----------+
         | cancel                  | cancel                 | cancel     |
         V                         V                        |            |   +-----------+
    +-----------+   finish   +------------+                 |            +-> |  Failed   |
    | Cancelled | <--------- | Cancelling | <---------------+                |(completed)|
    |(completed)|            +------------+                                  +-----------+
    +-----------+

A deferred value is a Job. A job in the coroutine context of async builder represents the coroutine itself. A deferred value is active while the coroutine is working and cancellation aborts the coroutine when the coroutine is suspended on a cancellable suspension point by throwing CancellationException or the cancellation cause inside the coroutine.

A deferred value can have a parent job. A deferred value with a parent is cancelled when its parent is cancelled or completes. Parent waits for all its children to complete in completing or cancelling state. Completing state is purely internal. For an outside observer a completing deferred is still active, while internally it is waiting for its children.

All functions on this interface and on all interfaces derived from it are thread-safe and can be safely invoked from concurrent coroutines without external synchronization.

Properties

isCompletedExceptionally

abstract val isCompletedExceptionally: Boolean

Returns true if computation of this deferred value has completed exceptionally – it had either failed with exception during computation or was cancelled.

onAwait

abstract val onAwait: SelectClause1<T>

Clause for select expression of await suspending function that selects with the deferred value when it is resolved. The select invocation fails if the deferred value completes exceptionally (either fails or it cancelled).

Inherited Properties

children

abstract val children: Sequence<Job>

Returns a sequence of this job’s children.

isActive

abstract val isActive: Boolean

Returns true when this job is active – it was already started and has not completed or cancelled yet. The job that is waiting for its children to complete is still considered to be active if it was not cancelled.

isCancelled

abstract val isCancelled: Boolean

Returns true if this job was cancelled. In the general case, it does not imply that the job has already completed (it may still be cancelling whatever it was doing).

isCompleted

abstract val isCompleted: Boolean

Returns true when this job has completed for any reason. A job that was cancelled and has finished its execution is also considered complete. Job becomes complete only after all its children complete.

onJoin

abstract val onJoin: SelectClause0

Clause for select expression of join suspending function that selects when the job is complete. This clause never fails, even if the job completes exceptionally.

Functions

await

abstract suspend fun await(): T

Awaits for completion of this value without blocking a thread and resumes when deferred computation is complete, returning the resulting value or throwing the corresponding exception if the deferred had completed exceptionally.

getCompleted

abstract fun getCompleted(): T

Returns completed result or throws IllegalStateException if this deferred value has not completed yet. It throws the corresponding exception if this deferred has completed exceptionally.

getCompletionExceptionOrNull

abstract fun getCompletionExceptionOrNull(): Throwable?

Returns completion exception result if this deferred completed exceptionally, null if it is completed normally, or throws IllegalStateException if this deferred value has not completed yet.

Inherited Functions

attachChild

abstract fun attachChild(child: Job): DisposableHandle

cancel

abstract fun cancel(cause: Throwable? = null): Boolean

Cancels this job with an optional cancellation cause. The result is true if this job was cancelled as a result of this invocation and false otherwise (if it was already completed or if it is NonCancellable). Repeated invocations of this function have no effect and always produce false.

getCancellationException

abstract fun getCancellationException(): CancellationException

Returns CancellationException that signals the completion of this job. This function is used by cancellable suspending functions. They throw exception returned by this function when they suspend in the context of this job and this job becomes complete.

invokeOnCompletion

abstract fun invokeOnCompletion(
    handler: CompletionHandler
): DisposableHandle

Registers handler that is synchronously invoked once on completion of this job. When job is already complete, then the handler is immediately invoked with a job’s exception or cancellation cause or null. Otherwise, handler will be invoked once when this job is complete.

abstract fun invokeOnCompletion(
    onCancelling: Boolean = false,
    invokeImmediately: Boolean = true,
    handler: CompletionHandler
): DisposableHandle

Registers handler that is synchronously invoked once on cancellation or completion of this job. When job is already cancelling or complete, then the handler is immediately invoked with a job’s cancellation cause or null unless invokeImmediately is set to false. Otherwise, handler will be invoked once when this job is cancelled or complete.

join

abstract suspend fun join(): Unit

Suspends coroutine until this job is complete. This invocation resumes normally (without exception) when the job is complete for any reason and the Job of the invoking coroutine is still active. This function also starts the corresponding coroutine if the Job was still in new state.

start

abstract fun start(): Boolean

Starts coroutine related to this job (if any) if it was not started yet. The result true if this invocation actually started coroutine or false if it was already started or completed.

Extension Functions

asPromise

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

Converts this deferred value to the instance of Promise.

cancel

fun CoroutineContext.cancel(
    cause: Throwable? = null
): Boolean

Cancels Job of this context with an optional cancellation cause. The result is true if the job was cancelled as a result of this invocation and false if there is no job in the context or if it was already cancelled or completed. See Job.cancel for details.

cancelAndJoin

suspend fun Job.cancelAndJoin(): Unit

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

cancelFutureOnCompletion

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

Cancels a specified future when this job is complete.

disposeOnCompletion

fun Job.disposeOnCompletion(
    handle: DisposableHandle
): DisposableHandle

Disposes a specified handle when this job is complete.

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.

Inheritors

CompletableDeferred

interface CompletableDeferred<T> : Deferred<T>

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