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

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 the default (else) action if none of them can be immediately selected.

List of supported select methods

ReceiverSuspending functionSelect clause

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. There is a prompt cancellation guarantee. If the job was cancelled while this function was suspended, it will not resume successfully. See suspendCancellableCoroutine documentation for low-level details.

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.


common source
Link copied to clipboard