簡體   English   中英

有沒有與RxJava的onDispose等效的Kotlin Coroutines Channel?

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

如果在RxJava中擴展Observable<> ,則可以重寫OnDispose()並執行清理操作,例如為垃圾收集器清除內容。

每當處置此Observable<>任何訂閱時,都會調用OnDispose()

但是,我似乎找不到協程通道的任何等效功能。

我知道channel.close(),但是不一樣。

有沒有辦法傳播

  • 暫停協程取消進入海峽; 要么
  • 訂閱處置/取消頻道?

我假設您在談論doOnDispose中的doOnDispose。 在這種情況下,您正在向通道發送元素,並且想知道下游何時取消了通道。 如果您在單個函數中構造生產代碼,則可以簡單地使用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!
    }
}

如果您的發送代碼很分散,並且您想接收取消回調,則可以使用SendChannel.invokeOnClose

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM