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 $it") }) }
This is the same program, but, just on comment (3), we added the defaultIfEmpty operator.
The output looks like the following screenshot:
The output shows that, although Observable doesn't contain any number above 10, defaultIfEmpty adds 15 to the Observable as it's empty after filtering.