Search code examples
javaandroidrx-javareactive-programmingrx-java2

RxJava, why 1 and 2 don't arrive in order in this sequence?


Observable.just(1, 2, 3, 4, 5)
    .flatMap(
        a -> {
          if (a < 3) {
            return Observable.just(a).delay(3, TimeUnit.SECONDS);
          } else {
            return Observable.just(a);
          }
        })
    .doOnNext(
        a -> System.out.println("Element: " + a )
    .subscribe();

If 1 and 2 wait 3 seconds, why sometimes 2 comes first and then 1? Shouldn't it always be 1 first?

sometimes:

Element: 3
Element: 4
Element: 5
Element: 2
Element: 1

and

Element: 3
Element: 4
Element: 5
Element: 1
Element: 2

shouldn't it always go out like this (3,4,5,1,2)?


Solution

  • By default delay operator uses computation scheduler :

        @CheckReturnValue
        @SchedulerSupport(SchedulerSupport.COMPUTATION)
        public final Observable<T> delay(long delay, TimeUnit unit) {
            return delay(delay, unit, Schedulers.computation(), false);
        }
    

    That means each delay operation is executed in a thread that is taken from computation pool.

    flatMap do not wait the last item was completely processed, So for 1 and 2 they are processed in different threads (taken from computation pool) in parallel. Different threads means no order guaranteed.

    All time based operators use computation scheduler by default. You can take a look to my other answer here