RxJava Operators: startWith(), defaultIfEmpty(), switchIfEmpty()

October 21, 2018

startWith()

With the help of the startWith() operator it is possible to insert an emission before all other emissions:

import io.reactivex.Observable;

public class Main {

    public static void main(String[] args) {
        Observable<String> myObservable = Observable.just("a", "b", "c");

        myObservable.startWith("First!")
                    .subscribe(System.out::println);
    }
}

In case you need to start with multiple items, you can use the startWithArray() operator:

import io.reactivex.Observable;

public class Main {

    public static void main(String[] args) {
        Observable<String> myObservable = Observable.just("a", "b", "c");

        myObservable.startWithArray("First!", "Second!", "Third!")
                    .subscribe(System.out::println);
    }
}

defaultIfEmpty()

The defaultIfEmpty() operator can be used if no emissions occured before the onComplete() was called:

import io.reactivex.Observable;

public class Main {

    public static void main(String[] args) {
        Observable<String> myObservable = Observable.just("a", "b", "c");

        myObservable.filter(s -> s.equals("x"))
                    .defaultIfEmpty("No element 'x' was found!")
                    .subscribe(System.out::println);
    }
}

switchIfEmpty()

The switchIfEmpty() operator is somewhat similar to the defaultIfEmpty() operator, it allows you to use a different Observable in case the original source is empty:

import io.reactivex.Observable;

public class Main {

    public static void main(String[] args) {
        Observable<String> myObservable = Observable.just("a", "b", "c");

        Observable<String> fallbackObservable = Observable.just("x", "y", "z");

        myObservable.filter(s -> s.equals("x"))
                    .switchIfEmpty(fallbackObservable)
                    .subscribe(System.out::println);
    }
}

 

András Döbröntey

About the Author

András Döbröntey

Leave a Comment:

Bitnami