invokeOnClose

@ExperimentalCoroutinesApi abstract fun invokeOnClose(
    handler: (cause: Throwable?) -> Unit
): Unit
(source)

Registers a handler which is synchronously invoked once the channel is closed or the receiving side of this channel is cancelled. Only one handler can be attached to a channel during its lifetime. The handler is invoked when isClosedForSend starts to return true. If the channel is closed already, the handler is invoked immediately.

The meaning of cause that is passed to the handler:

Example of usage (exception handling is omitted):

val events = Channel(UNLIMITED)
callbackBasedApi.registerCallback { event ->
  events.offer(event)
}

val uiUpdater = launch(Dispatchers.Main, parent = UILifecycle) {
   events.consume {}
   events.cancel()
}

events.invokeOnClose { callbackBasedApi.stop() }

Note: This is an experimental api. This function may change its semantics, parameters or return type in the future.

Exceptions

UnsupportedOperationException - if the underlying channel doesn’t support invokeOnClose. Implementation note: currently, invokeOnClose is unsupported only by Rx-like integrations

IllegalStateException - if another handler was already registered