Reputation: 45
This code begining in main thread, but i use subscribeOn
and observeOn
on Schedulers.io
disposableBag.add(Single.just(HardOperation.get())
.doOnSuccess(it -> {
Log.i("123", Thread.currentThread() + " current"); // Thread[RxCachedThreadScheduler-1,5,main]
})
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io()).subscribe(it -> {
adapter.set(it);
progressBar.setVisibility(View.GONE);
}));
if i use this sample
disposableBag.add(Single
.create((SingleOnSubscribe<List<Info>>) emitter -> {
emitter.onSuccess(HardOperation.get());
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()).subscribe(it -> {
adapter.set(it);
progressBar.setVisibility(View.GONE);
}));
it works nice
Upvotes: 0
Views: 1316
Reputation: 400
I think you are asking why HardOperation.get()
runs on main thread when called inside Single.just()
.
The reason is you are creating a Single
(subclass of Observable
) using Single.just()
. The code is evaluated from inside out, from inner most expression out. So, HardOperation.get()
is called first before being passed to Single.just()
. HardOperation.get()
will then take a while to complete and block the entire programs execution, before RxJava has a chance to do work on a different thread.
The difference of the second code snippet is that Single.create((SingleOnSubscribe<List<Info>>) emitter -> {emitter.onSuccess(HardOperation.get());})
creates a Single
by taking in an object that produces or emits a HardOperation.get()
. Creating this producer object is fast. Notice that emitter.onSuccess(HardOperation.get())
is not immediately called.
The producer is created and given to Single.create()
. It is RxJava's job to call the producer wrapped in the Single
on a different thread, which then calls HardOperation.get()
without blocking.
Upvotes: 2