Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ;)

like image 747
moskis Avatar asked Jan 04 '23 23:01

moskis


1 Answers

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();
like image 80
Tassos Bassoukos Avatar answered Jan 18 '23 03:01

Tassos Bassoukos