RxJava模式,用于请求具有临时缓存的远程Observable

Nei*_*lan 7 java android caching rx-java

用例是这样的:我想暂时缓存最新发出的昂贵的Observable响应,但是在它到期后,返回昂贵的源Observable并再次缓存它等.

一个非常基本的网络缓存场景,但我真的很难让它工作.

private Observable<String> getContentObservable() {

    // expensive upstream source (API, etc.)
    Observable<String> sourceObservable = getSourceObservable();

    // cache 1 result for 30 seconds, then return to the source
    return sourceObservable
            .replay(1, 30, TimeUnit.SECONDS)
            .autoConnect()
            .switchIfEmpty(sourceObservable);
}
Run Code Online (Sandbox Code Playgroud)

初始请求:转到源源发出的30秒内的第二个请求:从缓存传递缓存到期窗口之外的第三个请求:没有.我订阅它并且我没有获得数据,但它没有切换到上游源Observable.

看起来好像我只是连接到我的ConnectableObservable autoConnect()并且它永远不会用空填充,所以它永远不会触发我的switchIfEmpty().

我该如何使用replay(1,x,x)switchIfEmpty()?的组合?

或者我从一开始就接近这个错误?

Pho*_*ang 1

所以事实证明,即使在处理之后,您也可以使用 Jake Wharton 的重放共享来缓存最后一个值。 https://github.com/JakeWharton/RxReplayingShare