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 the same example as the previous one; just on comment (3), we used switchIfEmpty instead of defaultIfEmpty with an alternate Observable. The following output shows that the emissions were taken from the alternate Observable passed with the switchIfEmpty operator:

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

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