RxJava achieves concurrency through the Schedulers.
Most commonly used Schedulers are IO & Computation:
Schedulers.io : Used for IO bound tasks (e.g.network call or Database call.)
Schedulers.computation : Used for CPU bound tasks. (e.g. sorting large array in Java code)
The difference of CPU bound Vs IO bound task:
In case of IO bound task, we can have more theads , than, the no of CPU cores of running machine. Because CPU is idle when the IO operaion is called.
Whereas in case of CPU bound task, as it is purely computational (e.g. Performing sorting in Java ArrayList); hence we should avoid creating threads more than the no of CPU core in the running machine.
subscribeOn : runs the tasks in new thread (start to end)
observeOn : threading is applied only on the downstram task. (Operations defined after observeOn call)
Example:
In below example, we have taken a String , then transform the String to uppercase , then printed the value.
File Name: ObsSubsEx.java
import java.util.concurrent.TimeUnit;
import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;
public class ObsSubsEx {
public static void main(String[] args) throws InterruptedException {
Observable.just("subscribeOn One").subscribeOn(Schedulers.computation()).map(ObsSubsEx::toUpper).subscribe(ObsSubsEx::printVal);
TimeUnit.SECONDS.sleep(1);
Observable.just("subscribeOn Two").map(ObsSubsEx::toUpper).subscribeOn(Schedulers.computation()).subscribe(ObsSubsEx::printVal);
TimeUnit.SECONDS.sleep(1);
Observable.just("observeOn").map(ObsSubsEx::toUpper).observeOn(Schedulers.computation()).subscribe(ObsSubsEx::printVal);
TimeUnit.SECONDS.sleep(1);
}
private static String toUpper(String val) {
System.out.println("Uppercase done on thread:"+Thread.currentThread().getName());
return val.toUpperCase();
}
private static void printVal(String val) {
System.out.println("Final value is:"+val+":Thread:"+Thread.currentThread().getName());
}
}
No comments:
Post a Comment