简体   繁体   English

有没有与RxJava的onDispose等效的Kotlin Coroutines Channel?

[英]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. 如果在RxJava中扩展Observable<> ,则可以重写OnDispose()并执行清理操作,例如为垃圾收集器清除内容。

OnDispose() is called whenever any subscription to this Observable<> is disposed of. 每当处置此Observable<>任何订阅时,都会调用OnDispose()

However, I can't seem to find anything equivalent for Coroutine Channels. 但是,我似乎找不到协程通道的任何等效功能。

I am aware of channel.close(), but that is not the same. 我知道channel.close(),但是不一样。

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. 我假设您在谈论doOnDispose中的doOnDispose。 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 : 如果您在单个函数中构造生产代码,则可以简单地使用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 如果您的发送代码很分散,并且您想接收取消回调,则可以使用SendChannel.invokeOnClose

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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