The first and last operator

These operators help you listen only for the first or last emission and discard the remaining ones.

Check out the following example:

    fun main(args: Array<String>) { 
      val observable = Observable.range(1,10) 
      observable.first(2)//(1) 
       .subscribeBy { item -> println("Received $item") } 
 
      observable.last(2)//(2) 
       .subscribeBy { item -> println("Received $item") } 
 
      Observable.empty<Int>().first(2)//(3) 
       .subscribeBy { item -> println("Received $item") } 
    }

The output is as follows:

On comment (1), we used the first operator, with the defaultValue parameter set to 2 so that it will emit the defaultValue parameter if it can't access the first element. On comment (2), we used the last operator. On comment (3), we used the first operator again, this time, with an empty Observable; so, instead of emitting the first element, it emits defaultValue.

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

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