Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Schedulers.trampoline() inRxJava

Tags:

rx-java

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()?

like image 481
otal Avatar asked Oct 25 '16 07:10

otal


1 Answers

There is another usage for Schedulers.trampoline(), please check the following:

println("Current thread: ${Thread.currentThread()}")
Observable.interval(500, TimeUnit.MILLISECONDS, Schedulers.trampoline())
    .subscribe{
        println("$it thread: ${Thread.currentThread()}")
    }
println("This never will be reached")

If the one runs the code on the main thread then the result will be something like this:

Current thread: Thread[main,5,main]
0 thread: Thread[main,5,main]
1 thread: Thread[main,5,main]
2 thread: Thread[main,5,main]
3 thread: Thread[main,5,main]
4 thread: Thread[main,5,main]
5 thread: Thread[main,5,main]
...

And println("This never will be reached") will be reached never.

like image 80
Alexander Skvortsov Avatar answered Sep 20 '22 19:09

Alexander Skvortsov