I\'m in search for a better way to achieve a simple Observable fallback system for empty results when using RxJava. The idea is that, if a local query for a set of data results
Use switchIfEmpty
operator.
There is example of usage:
Observable.create(new Observable.OnSubscribe() {
@Override
public void call(Subscriber super String> subscriber) {
// return no item
//subscriber.onNext(...);
System.out.println("Generating nothing :)");
subscriber.onCompleted();
}
}).switchIfEmpty(Observable.create(new Observable.OnSubscribe() {
@Override
public void call(Subscriber super String> subscriber) {
System.out.println("Generating item");
subscriber.onNext("item");
subscriber.onCompleted();
}
})).subscribe(new Observer() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
System.out.println("onError");
}
@Override
public void onNext(String s) {
System.out.println("onNext: " + s);
}
});
Simplified with lamdas:
Observable.create(subscriber -> {
// return no item
//subscriber.onNext(...);
System.out.println("Generating nothing :)");
subscriber.onCompleted();
}).switchIfEmpty(Observable.create(subscriber -> {
System.out.println("Generating item");
subscriber.onNext("item");
subscriber.onCompleted();
})).subscribe(
s -> System.out.println("onNext: " + s),
throwable -> System.out.println("onError"),
() -> System.out.println("onCompleted")
);