Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does RxJava Parallelization Break the Observable Contract?

Ben Christensen posted here that the best way to currently achieve parallelism in RxJava is to create another Observable and subscribe it on a scheduler as shown below.

streamOfItems.flatMap(item -> {
   doStuffWithItem(item).subscribeOn(Schedulers.io());
});

However, the Observable Contract says that an onNext() call may be called any number of times, as long as the calls do not overlap. Well, any operators in the rest of the chain following the one above could now easily break that rule (unless they explicitly do some sort of synchronization/serialization).

My impression is RxJava prefers to keep a stream of emissions on one thread at a time and switching a steady sequential stream from one thread to another at specific operators, but never in parallel (as depicted below).

observeOn() thread     -------------------------Y----Y----Y-------------
subscribeOn() thread   ----X----X----X----X-----------------------------

With a parallel approach, I understand the chart may look something like this and that looks pretty overlapped to me.

par subscribeOn() thread 3    -------------------------Y-----Y---------------
par subscribeOn() thread 2    ---------------------------Y---Y---------------
par subscribeOn() thread 1    -------------------------Y-------------Y-------
initial subscribeOn() thread  ----X----X----X----X---------------------------

Did I misunderstand anything or make broad assumptions? Is parallelism not breaking the Observable contract? Does that make it not preferable in some way?

like image 864
tmn Avatar asked Sep 01 '26 10:09

tmn


1 Answers

If you are using standard operators, nothing will break the Observable contract because whenever concurrency may happen, the operators serialize their output. In your example, flatMap does this so its output is guaranteed to be sequential (although the the reception thread may switch back and forth).

This is, however, not generally true for different stages of the same pipeline if those are separated by an asynchronous boundary or an operator that may do thread arbitration.

like image 164
akarnokd Avatar answered Sep 03 '26 00:09

akarnokd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!