Fallback Observable for RxJava

前端 未结 6 1434
-上瘾入骨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:22

    Another variant. In my case I need to try one cached entry first, then lazily attempt the other if not present:

    public void test() {
        String cacheRowKey = "row";
        Observable = cacheLookup(cacheRowKey, "newVersion").switchIfEmpty(
            Observable.defer(() -> cacheLookup(cacheRowKey, "legacyVersion").switchIfEmpty(
            Observable.defer(() -> onMiss(cacheRowKey;
    }
    
    private Observable cacheLookup(String key, String version) {
        // Delegate to the real cache - will return effectively
        // Observable.just(xxx) or Observable.empty()
        ...
    }
    
    private Observable onMiss(String key) {
        // do the expensive lookup to then populate the cache
        ...
    }
    
    1. This first tries a lookup in cache for the key and 'new' version
    2. On cache miss, tries the cache again for the 'legacy' version
    3. On cache misses for both 'new' and 'legacy' versions, perform the expensive lookup (presumably to populate the cache).

    All of which are lazily done on demand.

提交回复
热议问题