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 ...

Get Reactive Programming in Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.