awaitClose

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

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

Note that when producer channel is cancelled this function resumes with cancellation exception, so putting the code after calling this function would not lead to its execution in case of cancellation. That is why this code takes a lambda parameter.

Example of usage:

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