3

Activity.runOnUiThread() has this:

if (Thread.currentThread() != mUiThread) {
    mHandler.post(action);
} else {
    action.run();
}

It means, it runs action immediately if I am in UI thread and posts action to handler if I am not. I am looking for RxJava Scheduler like this functionality. Does it exists?

cramopy
  • 3,459
  • 6
  • 28
  • 42
  • Possible duplicate of [RxJava timer that repeats forever, and can be restarted and stopped at anytime](https://stackoverflow.com/questions/38605090/rxjava-timer-that-repeats-forever-and-can-be-restarted-and-stopped-at-anytime) – KuLdip PaTel Oct 27 '17 at 06:36
  • The problem with running immediately is that if that `Runnable` also schedules on the main thread, you get a recursion that can lead to StackOverflowError or simply won't give up the main thread for other tasks. – akarnokd Oct 27 '17 at 07:31
  • @akarnokd Sorry but I can't understand you. Can you give an example? – ByungSun Park Oct 27 '17 at 08:38
  • @KuLdipPaTel Why do you think my question is duplicate of your suggestion? They are different problems. – ByungSun Park Oct 27 '17 at 08:44

1 Answers1

0

Yes it's simple.

getSomeObservable().observeOn(AndroidSchedulers.mainThread())

after .observeOn(AndroidSchedulers.mainThread()) you can subscribe to your observable and callbacks will come into main thread.

.subscribe(new Subscriber<Object>() {
                @Override
                public void onCompleted() {
                    Log.i(TAG,Thread.currentThread().getName());
                }

                @Override
                public void onError(Throwable e) {
                    Log.i(TAG,Thread.currentThread().getName());
                }

                @Override
                public void onNext(Object o) {
                    Log.i(TAG,Thread.currentThread().getName());
                }
            });
Dmitriy Puchkov
  • 1,530
  • 17
  • 41
  • The `AndroidSchedulers.mainThread` [always posts](https://github.com/ReactiveX/RxAndroid/blob/2.x/rxandroid/src/main/java/io/reactivex/android/schedulers/HandlerScheduler.java#L72), even if the `schedule` call is on the main thread. – akarnokd Oct 27 '17 at 08:07
  • Yes I see. May be Observable.just() will suite, as I know it doing action immediately. – Dmitriy Puchkov Oct 27 '17 at 10:54
  • `just` doesn't run on any particular scheduler. You need an operator that can move subscription/observation to the main thread. – akarnokd Oct 27 '17 at 12:22