...

/

Schedulers with Operators

Schedulers with Operators

Learn how Schedulers are used in conjunction with the .subscribeOn() and .observeOn() operators.

.subscribeOn()

The .subscribeOn() operator is used in the Observable chain to dictate where the Observable should operate–for example, the function inside of .create(). Rewriting the previous example using a Scheduler instead gives us:

Press + to interact
Observable<Integer> integerObservable = Observable.create(source -> {
Log.d(TAG, "In subscribe");
source.onNext(1);
source.onNext(2);
source.onNext(3);
source.onComplete();
});
Log.d(TAG, "Created Observable");
Log.d(TAG, "Subscribing to Observable");
integerObservable.subscribeOn(Schedulers.newThread())
.subscribe(i -> Log.e(TAG, "In onNext(): " + i));
Log.d(TAG, "Finished");

Running the above code is similar to using a Thread in that the operations inside .create() now occurs in a separate thread provided by Schedulers.newThread(). The benefit of this approach over using a Thread is that tacking on a Scheduler to specify where the Observable should ...