RxJava and parallel execution of observer code

前端 未结 5 715
一整个雨季
一整个雨季 2020-12-04 14:18

I am having the following code using RxJava Observable api :

Observable observable = fileProcessor.processFileObservable(processedFile.getAbsolut         


        
5条回答
  •  有刺的猬
    2020-12-04 15:08

    RxJava 2.0.5 introduced parallel flows and ParallelFlowable, which makes parallel execution simpler and more declarative.

    You no longer have to create Observable/Flowable within flatMap, you can simply call parallel() on Flowable and it returns ParallelFlowable.

    It's not as feature rich as a regular Flowable, because concurrency raises many issues with Rx contracts, but you have basic map(), filter() and many more, which should be enough in most cases.

    So instead of this flow from @LordRaydenMK answer:

    Observable vals = Observable.range(1,10);
    
    vals.flatMap(val -> Observable.just(val)
            .subscribeOn(Schedulers.computation())
            .map(i -> intenseCalculation(i))
        ).subscribe(val -> System.out.println(val));
    

    Now you can do:

    Flowable vals = Flowable.range(1, 10);
    
    vals.parallel()
            .runOn(Schedulers.computation())
            .map(i -> intenseCalculation(i))
            .sequential()
            .subscribe(val -> System.out.println(val));
    

提交回复
热议问题