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 ;)
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With