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 found a more elegant solution to this problem.
Observable cachedObservable =
Observable.from(Collections.emptyList()) // Swap this line with the below one to test the different cases
//Observable.from(Arrays.asList("1", "2"))
.cache();
cachedObservable.isEmpty().switchMap(isEmpty -> {
if (isEmpty)
return Observable.from("3", "4");
else
return cachedObservable;
}).subscribe(System.out::println);
The key contender here is cache
which replays the original emitted values.
Keep in mind the javadoc about cache
.
You sacrifice the ability to unsubscribe from the origin when you use the cache Observer so be careful not to use this Observer on Observables that emit an infinite or very large number of items that will use up memory.