The switchIfEmpty operator

This operator is similar to the defaultIfEmpty operator; the only difference is that, for the defaultIfEmpty operator, it adds an emission to empty producers, but for the switchIfEmpty operator, it starts emitting from the specified alternative producer if the source producer is empty.

Unlike the defaultIfEmpty operator, where you needed to pass an item, here, you have to pass an alternate producer to the switchIfEmpty operator. If the source producer is empty, it will start taking emissions from the alternate producer.

Here is an example:

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

This is ...

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.