Search code examples
rx-javarx-androidrx-java2reactivex

Rx2 blockingFirst() doesn't work


I am introducing in the rx world and I want to understand why blocking does not work when I subscribe to newThread. For example:

This is working:

int i = Observable.fromArray(1,2,3,4).blockingFirst();

This is not working:

int i = Observable.just(1,2,3,4)
      .subscribeOn(Schedulers.newThread())
      .observeOn(AndroidSchedulers.mainThread()).blockingFirst();

And if is posible to make the second case works.

Thanks ;)


Solution

  • The operator observeOn(AndroidSchedulers.mainThread()) will queue all emitted items to be emitted in the main thread of the Android application. If you execute the above snippet in the main thread, the thread will block in the blockingFirst method, and will not have any chance to execute the queued instructions for the items - it's a deadlock.

    In general, using blocking in Rx code is an anti-pattern; it's easier to just remain in reactive mode and do something like:

    Observable
    .just(1,2,3,4)
    .subscribeOn(Schedulers.newThread())
    .observeOn(AndroidSchedulers.mainThread())
    .doOnNext(i -> {...})
    .subscribe();