简体   繁体   English

如何进行多个异步(RX)调用,并等待它们在 Kotlin 中完成?

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

I am trying to find a way to run some code after 3 async rx-fun's have finished.我正在尝试找到一种在 3 个异步 rx-fun 完成后运行一些代码的方法。

Does anyone know a good way to do this by using RX?有谁知道使用 RX 的好方法吗?

I'm very new to this subject and don't have any runnable code to show, but I can say that the way I solve the problem in my code right now is by setting 3 Booleans to true after the async part of each fun has finished, and then in my code which is waiting, I am running a 4th function (RX Flowable) which I have subsrcibed to that checks if all 3 Booleans are true.我对这个主题很陌生,没有任何可运行的代码要显示,但我可以说我现在在代码中解决问题的方法是在每个乐趣的异步部分之后将 3 个布尔值设置为 true完成,然后在我正在等待的代码中,我正在运行第 4 个 function(RX Flowable),我已订阅它检查所有 3 个布尔值是否为真。

It looks a little like this:它看起来有点像这样:

// 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()
 }

You can use Completable.merge with the various methods run async via subscribeOn :您可以将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