How to watch the calling thread in java rx?

anyway, to tell java rx to use the current thread in the observOn function? I am writing code for the syncadapter android and want the results to be observed in the sync adapter thread, and not in the main thread.

An example of a network call with Retrofit + RX Java looks something like this:

MyRetrofitApi.getInstance().getObjects() .subscribeOn(Schedulers.io()) .observeOn(<current_thread>) .subscribe(new Subscriber<Object>() { //do stuff on the sync adapter thread } 

I tried to use

 ... .observeOn(AndroidSchedulers.handlerThread(new Handler(Looper.myLooper()))) ... 

similar to how android rx creates a scheduler for the main thread, but it no longer works as soon as I submenu Looper.myLooper() for Looper.getMainLooper() .

I could use Schedulers.newThread (), but as a complex synchronization code with a lot of server calls, I would constantly create a new thread to start new network calls, which again create new threads to start more network calls. Is there any way to do this? Or is my approach completely wrong?

+7
rx-java rx-android android-syncadapter
source share
2 answers

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โ€™s ok to work on the SyncAdapter thread, because it already uses a different thread

+3
source share

Oh, I just found this on the wiki: 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 business too - besides creating a new topic, of course ... It's so simple:

 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 } 
+1
source share

All Articles