The defaultIfEmpty operator

While working with filtering operators and/or working on complex requirements, it may occur that we encounter an empty producer (see the following code block):

    fun main(args: Array<String>) { 
      Observable.range(0,10)//(1) 
       .filter{it>15}//(2) 
       .subscribe({ 
         println("Received $it") 
      }) 
    } 

Here, on comment (1), we will create Observable of range 0 to 10; however, on comment (2), we will filter it for emission value >15. So, basically, we will end up with an empty Observable.

The defaultIfEmpty operator helps us deal with such situations. The preceding example, with defaultIfEmpty looks like this:

 fun main(args: Array<String>) { Observable.range(0,10)//(1) .filter{it>15}//(2) .defaultIfEmpty(15)//(3) .subscribe({ println("Received ...

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.