invokeOnClose

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

Registers handler which is synchronously invoked once the channel is closed or receiving side of this channel is cancelled. Only one handler can be attached to the channel during channel’s lifetime. Handler is invoked when isClosedForSend starts to return true. If channel is already closed, 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(UI, 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 underlying channel doesn’t support invokeOnClose. Implementation note: currently, invokeOnClose is unsupported only by Rx-like integrations

IllegalStateException - if another handler was already registered