简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM