Is there a Kotlin Coroutines Channel equivalent of RxJava's onDispose?

970 views Asked by At

If I extend an Observable<> in RxJava, I can override OnDispose(), and perform cleaning up such as clearing things for the Garbage Collector.

OnDispose() is called whenever any subscription to this Observable<> is disposed of.

However, I can't seem to find anything equivalent for Coroutine Channels.

I am aware of channel.close(), but that is not the same.

Is there some way to propagate either

  • suspended coroutine cancellation to the Channel; or
  • subscription disposal/cancellation to the Channel?
1

There are 1 answers

2
Roman  Elizarov On

I assume you talking about doOnDispose in RxJava. In this case you are sending elements to the channel and would like to know when the downstream had cancelled the channel. If you structure your producing code in a single function, then you can simply use try/finally:

val channel = produce { 
    // channel producing code is here
    try {
        // this example is sending 10 ints, but it can be any other code
        repeat(10) { send(it) }
    } finally {
        // doOnDispose here!
    }
}

If your sending code is spread-out and you'd like to receive a cancellation callback then you can use SendChannel.invokeOnClose