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
I'm sure there's more elegant solution to this problem but you could simply use flatMap in this case. Since you're already dealing the List
which is returned from queryLocalDatabase()
method you could do something like this.
Observable.create(new Observable.OnSubscribe>() {
@Override
public void call(Subscriber super List> subscriber) {
List results = queryLocalDatabase();
subscriber.onNext(results);
subscriber.onCompleted();
}
private List queryLocalDatabase() {
return Arrays.asList();
}
}).flatMap(new Func1, Observable>() {
@Override
public Observable call(List list) {
if (list.isEmpty()) {
return getFallbackObservable();
} else {
return Observable.from(list);
}
}
private Observable getFallbackObservable() {
return Observable.from("3", "4");
}
}).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);
}
});
I've replace Object for String for the purpose of this code.