简体   繁体   中英

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.

Does anyone know a good way to do this by using 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.

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.mergeArray(
   Completable.fromAction { async1() }.subscribeOn(Schedulers.io()),
   Completable.fromAction { async2() }.subscribeOn(Schedulers.io()),
   Completable.fromAction { async3() }.subscribeOn(Schedulers.io())
)
.andThen(Flowable...)

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