RxJava - Trampoline Scheduler

RxJava - Trampoline Scheduler

This scheduler runs the code on current thread. So if you have a code running on the main thread, this scheduler will add the code block on the queue of main thread. It is quite similar to Immediate Scheduler as it also blocks the thread, however, it waits for the current task to execute completely(while Immediate Scheduler invokes the task right away). Trampoline schedulers come in handy when we have more than one observable and we want them to execute in order

 

Example

public class RxSchedulers {
    
    public static void main(String[] args)
    {
        Observable.just(1,2,3,4)
    .subscribeOn(Schedulers.trampoline())
    .subscribe(s->System.out.println(s));
        Observable.just( 5,6, 7,8, 9)
    .subscribeOn(Schedulers.trampoline())
    .subscribe(s->System.out.println(s));
    }
}

 

Output

1
2
3
4
5
6
7
8
9

 

Example 2:

public class RxSchedulers {
    
    public static void main(String[] args) throws InterruptedException
    {

        
          Observable.just("A", "AB", "ABC")
         .flatMap(v -> getLengthWithDelay(v)
         .doOnNext(s -> System.out.println("Processing Thread " 
            + Thread.currentThread().getName()))
         .subscribeOn(Schedulers.trampoline()))
         .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 main
Receiver Thread main, Item length 1
Processing Thread main
Receiver Thread main, Item length 2
Processing Thread main
Receiver Thread main, Item length 3