RxJava - IO Scheduler

RxJava - IO Scheduler

This Scheduler is similar to the newThread except for the fact that already started threads are recycled and can possibly handle future requests.

This implementation works similarly to ThreadPoolExecutor from java.util.concurrent with an unbounded pool of threads. Every time a new worker is requested, either a new thread is started (and later kept idle for some time) or the idle one is reused

Example:

public class RxSchedulers {
    
    public static void main(String[] args) throws InterruptedException
    {
        
         Observable.just("Rx", "Java", "Scheduler")
         .flatMap(v -> getLengthWithDelay(v)
         .doOnNext(s -> System.out.println("Processing Thread " 
            + Thread.currentThread().getName()))
         .subscribeOn(Schedulers.io()))
         .subscribe(length -> System.out.println("Receiver Thread " 
            + Thread.currentThread().getName() 
            + ", Item length " + length));

         Thread.sleep(10000);
   }
   protected static Observable<Integer> getLengthWithDelay(String v) {
      Random random = new Random();
      try {
         Thread.sleep(random.nextInt(3) * 1000);
         return Observable.just(v.length());
      } catch (InterruptedException e) {
         e.printStackTrace();
      }
      return null;
   }

}

Output:

Processing Thread RxCachedThreadScheduler-2
Processing Thread RxCachedThreadScheduler-3
Processing Thread RxCachedThreadScheduler-1
Receiver Thread RxCachedThreadScheduler-2, Item length 4
Receiver Thread RxCachedThreadScheduler-1, Item length 2
Receiver Thread RxCachedThreadScheduler-1, Item length 9