Fallback Observable for RxJava

前端 未结 6 1431
-上瘾入骨i
-上瘾入骨i 2021-02-02 00:25

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

6条回答
  •  有刺的猬
    2021-02-02 01:19

    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.

提交回复
热议问题