Sign in Go Pro

RxJava

RxJava Operators - observeOn

 
Autoplay

Up next

Previous

About

This lesson will go over how to leverage the ObserveOn operator to change threads within an RxJava observable chain. We'll be going over how to change from a background thread to the main thread as well as how to use schedulers to create an IO thread for savings to a database.

Instructor

Links

Comments

I was testing this in rx java 2.

Here's my code:

Observable
.fromCallable(new Callable() {
@Override
public String call(){
Log.d("RX", "Callable processing STARTED");
SystemClock.sleep(4000);
Log.d("RX", "Callable processing COMPLETED");

return "Hello Caster Students";

}
})
.subscribeOn(Schedulers.computation())
.observeOn(Schedulers.io())
.doOnNext(new Consumer() {

@Override
public void accept(String s) throws Exception {
Log.d("RX", "Next task STARTED");
SystemClock.sleep(4000);
Log.d("RX", "Next task COMPLETED");
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer() {
@Override
public void accept(String s) throws Exception {
Log.d("RX", "Observabled Completed Result Processing STARTED");
Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();
Log.d("RX", "Observabled Completed Result Processing ENDED");
}

});

Here's the output:

08-15 22:00:20.927 24274-24420/com.example.ranjithchaz.reactiveplaygroud D/RX: Callable processing STARTED
08-15 22:00:24.928 24274-24420/com.example.ranjithchaz.reactiveplaygroud D/RX: Callable processing COMPLETED
08-15 22:00:24.930 24274-24931/com.example.ranjithchaz.reactiveplaygroud D/RX: Next task STARTED
08-15 22:00:28.932 24274-24931/com.example.ranjithchaz.reactiveplaygroud D/RX: Next task COMPLETED
08-15 22:00:28.936 24274-24274/com.example.ranjithchaz.reactiveplaygroud D/RX: Observabled Completed Result Processing STARTED
08-15 22:00:28.940 24274-24274/com.example.ranjithchaz.reactiveplaygroud D/RX: Observabled Completed Result Processing ENDED


As you can see, from the time of the logs, toast is printed only after the 'doOnNext' is finished execution. Am I missing something?

>
You need to go PRO to post comments.

Lessons in RxJava