Schedulers.trampoline()

Schedulers.single() and Schedulers.trampoline() sound somewhat similar, both the schedulers are for sequential execution. While Schedulers.single() guarantees that all its task will run sequentially, it may run parallel to the thread it was called upon (if not, that thread is from Schedulers.single() as well); the Schedulers.trampoline() is different in that sector.

Unlike maintaining a thread to its disposal like Schedulers.single(), Schedulers.trampoline() queues up the task on the thread it was called on.

So, it'll be sequential with the thread it was called upon.

Let's look at some examples of Schedulers.single() and Schedulers.trampoline() to understand them better:

    fun main(args: Array<String>) { 
 
      async(CommonPool) { 
        Observable.range(1, 10) 
          .subscribeOn(Schedulers.single())//(1) 
          .subscribe { 
             runBlocking { delay(200) } 
             println("Observable1 Item Received $it") 
           } 
 
         Observable.range(21, 10) 
           .subscribeOn(Schedulers.single())//(2) 
           .subscribe { 
              runBlocking { delay(100) } 
              println("Observable2 Item Received $it") 
            } 
 
          for (i in 1..10) { 
            delay(100) 
            println("Blocking Thread $i") 
          } 
        } 
 
       runBlocking { delay(6000) } 
    } 

The output is as follows:

The output clearly shows that despite the fact that both the subscriptions run sequentially, they run in parallel to the calling thread.

Now, let's implement the same code with Schedulers.trampoline() and observe the difference:

    fun main(args: Array<String>) { 
 
      async(CommonPool) { 
        Observable.range(1, 10) 
          .subscribeOn(Schedulers.trampoline())//(1) 
          .subscribe { 
              runBlocking { delay(200) } 
              println("Observable1 Item Received $it") 
          } 
 
          Observable.range(21, 10) 
            .subscribeOn(Schedulers.trampoline())//(2) 
            .subscribe { 
               runBlocking { delay(100) } 
               println("Observable2 Item Received $it") 
             } 
 
          for (i in 1..10) { 
            delay(100) 
            println("Blocking Thread $i") 
          } 
       } 
 
       runBlocking { delay(6000) } 
    } 

The following output shows that the scheduler ran sequentially to the calling thread:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.17.128