How to use Schedulers.trampoline() inRxJava

rx-java

Solution

you would not gain any benefits from using the scheduler in observeOn/ subscribeOn. You would use the Worker from the scheduler to schedule work after work.

Please have a look at the example. I am using RxJava2-RC5

@Test
public void trampoline() throws Exception {
        Scheduler scheduler = Schedulers.trampoline();
        Scheduler.Worker worker = scheduler.createWorker();

        Runnable r1 = () -> {
            System.out.println("Start: r1");
            System.out.println("End: r1");
        };

        Runnable r2 = () -> {
            System.out.println("Start: r2");
            worker.schedule(r1);
            System.out.println("End: r2");
        };

        worker.schedule(r2);
}

Output:

Start: r2 End: r2 Start: r1 End: r1

The trampoline worker comes in handy, if you are scheduling work recursively, because you would not get and StackOverFlow.

The example was rephrased to RxJava from introtorx (http://www.introtorx.com/content/v1.0.10621.0/15_SchedulingAndThreading.html)

Problem

Since `Schedulers.trampoline()` makes the job work on the current thread, I cannot find the difference between the case with `Schedulers.trampoline()` and the case without Schedulers settings. Using `Schedulers.trampoline()`: ``` Observable.from(1, 2, 3) .observeOn(Schedulers.trampoline()) .subscribe(System.out::println) ``` Not Using Schedulers: ``` Observable.from(1, 2, 3) .subscribe(System.out::println) ``` I think that above codes act the same. I really wonder why `Schedulers.trampoline()` exists in RxJava's API. In what situation, should I use `Schedulers.trampoline()`?

Original source