The elementAt operator

With imperative programming, we have the ability to access the nth element of any array/list, which is quite a common requirement. The elementAt operator is really helpful in this regard; it pulls the nth element from the producer and emits it as its own sole emission.

Take a look at the following piece of code:

    fun main(args: Array<String>) { 
      val observable = listOf(10,1,2,5,8,6,9) 
        .toObservable() 
 
      observable.elementAt(5)//(1) 
        .subscribe { println("Received $it") } 
 
      observable.elementAt(50)//(2) 
        .subscribe { println("Received $it") } 
    } 

Take a look at the following output before we continue to inspect the code:

On comment (1), we requested the 5th element from Observable, and it emitted the same (count starts with zero). However, on comment (2), we requested the 50th element, which doesn't even exist in Observable, so it didn't emit anything.

This operator achieves this behavior with the help of the Maybe monad, which will be covered later.

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

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