1

I want observable code to run on different thread than main thread. How can I do this, I'm doing like this:

Observable operationObservable = Observable.create(new ObservableOnSubscribe() {
        @Override
        public void subscribe(ObservableEmitter e) throws Exception {
            e.onNext(longRunningOperation());
            e.onComplete();
        }
    })
    .subscribeOn(Schedulers.io()) // subscribeOn the I/O thread
    .observeOn(AndroidSchedulers.mainThread());
Jemshit
  • 9,501
  • 5
  • 69
  • 106
blackHawk
  • 6,047
  • 13
  • 57
  • 100
  • Well, try using a different thread in `observeOn`? – OneCricketeer Oct 17 '17 at 13:47
  • You can instruct an `Observable` to send its notifications to observers on a particular Scheduler by means of the `ObserveOn` operator. by that you can use your `Scheduler` or class which implements `Scheduler` to observe – Kathi Oct 17 '17 at 14:01
  • Your example does exactly that. `subscribeOn` will make sure the body of the `ObservableOnSubscribe.subscribe` is executing in one of the IO threads of the IO Scheduler. – akarnokd Oct 17 '17 at 14:06

1 Answers1

2

If you need a new thread to run something on you can just use subscribeOn(Schedulers.newThread()).

Another alternative would be to create your own scheduler and executors which is really not necessary for most cases.

Further reading: link1 link2 link3

SoroushA
  • 2,043
  • 1
  • 13
  • 29