select

inline suspend fun <R> select(
    crossinline builder: SelectBuilder<R>.() -> Unit
): R
(source)

Platform and version requirements: JVM

Waits for the result of multiple suspending functions simultaneously, which are specified using clauses in the builder scope of this select invocation. The caller is suspended until one of the clauses is either selected or fails.

At most one clause is atomically selected and its block is executed. The result of the selected clause becomes the result of the select. If any clause fails, then the select invocation produces the corresponding exception. No clause is selected in this case.

This select function is biased to the first clause. When multiple clauses can be selected at the same time, the first one of them gets priority. Use selectUnbiased for an unbiased (randomized) selection among the clauses.

There is no default clause for select expression. Instead, each selectable suspending function has the corresponding non-suspending version that can be used with a regular when expression to select one of the alternatives or to perform default (else) action if none of them can be immediately selected.

Receiver Suspending function Select clause Non-suspending version
Job join onJoin isCompleted
Deferred await onAwait isCompleted
SendChannel send onSend offer
ReceiveChannel receive onReceive poll
ReceiveChannel receiveOrNull onReceiveOrNull poll
Mutex lock onLock tryLock
none delay onTimeout none

This suspending function is cancellable. If the Job of the current coroutine is cancelled or completed while this function is suspended, this function immediately resumes with CancellationException.

Atomicity of cancellation depends on the clause: onSend, onReceive, onReceiveOrNull, and onLock clauses are atomically cancellable. When select throws CancellationException it means that those clauses had not performed their respective operations. As a side-effect of atomic cancellation, a thread-bound coroutine (to some UI thread, for example) may continue to execute even after it was cancelled from the same thread in the case when this select operation was already resumed on atomically cancellable clause and the continuation was posted for execution to the thread’s queue.

Note, that this function does not check for cancellation when it is not suspended. Use yield or CoroutineScope.isActive to periodically check for cancellation in tight loops if needed.