Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flowable.parallel vs Flowable.flatMap?

RxJava 2.0.5 introduced the ParallelFlowable type, corresponding to the Flowable.parallel() operator. I've found that the general advice for achieving parallelism is with flatMap like so:

Flowable.just(1,2,3)
    .flatMap(x -> Flowable.just(x)
        .observeOn(Schedulers.computation())
        .map(y -> y + 1))
    .forEach(System.out::println);

When is it appropriate to use flatMap for parallelism, and when is it better to use ParallelFlowable?

like image 678
zls88 Avatar asked May 31 '17 17:05

zls88


1 Answers

I've found that the general advice for achieving parallelism is with flatMap like so:

Those advises come from before the introduction of parallel so API evolution since then should be considered.

When is it appropriate to use flatMap for parallelism, and when is it better to use ParallelFlowable?

ParallelFlowable has a limited set of operators: map, filter, doOnNext, reduce, flatMap, etc. instead of the full blown Flowable API. Thus if you have something "exotic" to do in parallel which can't be expressed with the operators above, you should stick to Flowable.flatMap based parallelism (or consider groupBy parallelism).

Otherwise, here is a benchmark comparison between the parallelization approaches (code).

like image 171
akarnokd Avatar answered Nov 02 '22 19:11

akarnokd