invokeOnClose

open override fun invokeOnClose(handler: Handler)

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:

  • null if the channel was closed or cancelled without the corresponding argument

  • the cause of close or cancel otherwise.

Example of usage (exception handling is omitted):

val events = Channel(UNLIMITED)
callbackBasedApi.registerCallback { event ->
events.trySend(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.

Throws

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

if another handler was already registered

Sources

common source
Link copied to clipboard