How to observeOn the calling thread in java rx?
is there anyway to tell java rx to use the current thread in the observeOn function? I am writing code for the android syncadapter and I want the results be observed in the sync adapter thread and not in the main thread.
An example network call with Retrofit + RX Java looks something like that:
MyRetrofitApi.getInstance().getObjects()
.subscribeOn(Schedulers.io())
.observeOn(<current_thread>)
.subscribe(new Subscriber<Object>() {
//do stuff on the sync adapter thread
}
I tried using using
...
.observeOn(AndroidSchedulers.handlerThread(new Handler(Looper.myLooper())))
...
which is the same way android rx creates the scheduler for the main thread but doesn't work anymore as soon as I substitute Looper.myLooper()
for Looper.getMainLooper()
.
I could use the Schedulers.newThread() but as its complex syncing code with a lot of server calls I would be constantly creating a new thread just to fire new network calls that again create new threads to to launch more network calls. Is there a way to do this? Or is my approach itself completly wrong?
Try Using Schedulers.immediate()
MyRetrofitApi.getInstance().getObjects()
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.immediate())
.subscribe(new Subscriber<Object>() {
//do stuff on the sync adapter thread
}
Its description says: Creates and returns a Scheduler that executes work immediately on the current thread.
NOTE:
I think it is okay to keep all the work on the SyncAdapter's thread because it is already using a different thread
Oh, I just found this in the wiki at: https://github.com/ReactiveX/RxAndroid#observing-on-arbitrary-threads
new Thread(new Runnable() {
@Override
public void run() {
final Handler handler = new Handler(); // bound to this thread
Observable.just("one", "two", "three", "four", "five")
.subscribeOn(Schedulers.newThread())
.observeOn(HandlerScheduler.from(handler))
.subscribe(/* an Observer */)
// perform work, ...
}
}, "custom-thread-1").start();
I think this should work for your case, too - except the creation of a new Thread, of course... So just:
final Handler handler = new Handler(); // bound to this thread
MyRetrofitApi.getInstance().getObjects()
.subscribeOn(Schedulers.io())
.observeOn(HandlerScheduler.from(handler))
.subscribe(new Subscriber<Object>() {
//do stuff on the sync adapter thread
}
链接地址: http://www.djcxy.com/p/88956.html
上一篇: strings.xml中的Android`templateMergeStrategy`
下一篇: 如何观察java rx中的调用线程?