Combine a list of Observables and wait until all completed

前端 未结 8 1100
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 06:35

TL;DR How to convert Task.whenAll(List) into RxJava?

My existing code uses Bolts to build up a list of asynchr

8条回答
  •  被撕碎了的回忆
    2020-12-04 07:02

    I'm writing some computation heave code in Kotlin with JavaRx Observables and RxKotlin. I want to observe a list of observables to be completed and in the meantime giving me an update with the progress and latest result. At the end it returns the best calculation result. An extra requirement was to run Observables in parallel for using all my cpu cores. I ended up with this solution:

    @Volatile var results: MutableList = mutableListOf()
    
    fun doALotOfCalculations(listOfCalculations: List): Observable> {
    
        return Observable.create { subscriber ->
            Observable.concatEager(listOfCalculations.map { calculation: Calculation ->
                doCalculation(calculation).subscribeOn(Schedulers.computation()) // function doCalculation returns an Observable with only one result
            }).subscribeBy(
                onNext = {
                    results.add(it)
                    subscriber.onNext(Pair("A calculation is ready", it))
    
                },
                onComplete = {
                    subscriber.onNext(Pair("Finished: ${results.size}", findBestCalculation(results)) 
                    subscriber.onComplete()
                },
                onError = {
                    subscriber.onError(it)
                }
            )
        }
    }
    

提交回复
热议问题