...

/

Schedulers and Publishers

Schedulers and Publishers

Learn about Schedulers and Publishers for heavy computations in Java.

We'll cover the following...

For some heavy computations, we may want to run them in the background, while rendering the result in a separate thread so as not to block the UI or rendering thread. For this case, we can use the observeOn method with a different Scheduler.

public static void runComputation() throws Exception {
   StringBuffer sb = new StringBuffer();
   Flowable<String> source = Flowable.fromCallable(() -> { //1
      Thread.sleep(1000); // imitate expensive computation
      return "Done";
   });
source.doOnComplete(() -> System.out.println("Completed runComputation"));

Flowable<String> background = source.subscribeOn(Schedulers.io()); //2

Flowable<String> foreground = background.observeOn(Schedulers.single());//3

foreground.subscribe(System.out::println, Throwable::printStackTrace);//4
}
  1. Create a new Flowable from a
...