簡體   English   中英

如何進行多個異步(RX)調用,並等待它們在 Kotlin 中完成?

[英]How to make several async (RX) calls, and wait for them to finish in Kotlin?

我正在嘗試找到一種在 3 個異步 rx-fun 完成后運行一些代碼的方法。

有誰知道使用 RX 的好方法嗎?

我對這個主題很陌生,沒有任何可運行的代碼要顯示,但我可以說我現在在代碼中解決問題的方法是在每個樂趣的異步部分之后將 3 個布爾值設置為 true完成,然后在我正在等待的代碼中,我正在運行第 4 個 function(RX Flowable),我已訂閱它檢查所有 3 個布爾值是否為真。

它看起來有點像這樣:

// var async1IsDoneBoolean = false
// var async2IsDoneBoolean = false
// var async3IsDoneBoolean = false

fun async1() {
    // Start async work {
    // working..
    // done!
    // async1IsDoneBoolean = true
    // }
}
fun async2() {
    // Start async work {
    // working..
    // done!
    // async2IsDoneBoolean = true
    // }
}
fun async3() {
    // Start async work {
    // working..
    // done!
    // async3IsDoneBoolean = true
    // }
}

fun useResulfOfAsyncFuns() {
    // Create and subscribe to RX Flowable (will repeat until unsubscribed)
    // if (async1IsDoneBoolean && async2IsDoneBoolean && async3IsDoneBoolean) {
    // Run code after all async is done
    // }
}

 main() {
    async1()
    async2()
    async3()
    useResulfOfAsyncFuns()
 }

您可以將Completable.merge與通過subscribeOn異步運行的各種方法一起使用:

Completable.mergeArray(
   Completable.fromAction { async1() }.subscribeOn(Schedulers.io()),
   Completable.fromAction { async2() }.subscribeOn(Schedulers.io()),
   Completable.fromAction { async3() }.subscribeOn(Schedulers.io())
)
.andThen(Flowable...)

暫無
暫無

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

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