February 2020
Intermediate to advanced
412 pages
9h 36m
English
If we want to resort to a single emission when a given Observable turns out to be empty, we can use defaultIfEmpty(). For example, if we have an Observable<String> and filter only items that start with Z, we can resort to emitting None:
import io.reactivex.rxjava3.core.Observable;public class Ch3_03 { public static void main(String[] args) { Observable<String> items = Observable.just("Alpha", "Beta"); items.filter(s -> s.startsWith("Z")) .defaultIfEmpty("None") .subscribe(System.out::println); }}
The output of the preceding code snippet is as follows:
None
Of course, if emissions were to occur, we would never see the message None. It happens only when the source Observable is empty.
Read now
Unlock full access