awaitClose

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

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: if the Job of the current coroutine is cancelled while this suspending function is waiting, this function immediately resumes with CancellationException. There is a prompt cancellation guarantee: even if this function is ready to return, but was cancelled while suspended, CancellationException will be thrown. See suspendCancellableCoroutine 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() }
}