awaitClose

suspend fun ProducerScope<*>.awaitClose(block: () -> Unit = {})

Suspends the current coroutine until the channel is either closed or cancelled and invokes the given block before resuming the coroutine.

This suspending function is cancellable. 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 when the producer channel is cancelled, this function resumes with a cancellation exception. Therefore, in case of cancellation, no code after the call to this function will be executed. That's why this function takes a lambda parameter.

Example of usage:

val callbackEventsStream = produce {
val disposable = registerChannelInCallback(channel)
awaitClose { disposable.dispose() }
}

Sources

common source
Link copied to clipboard