RxJava模式,用于请求具有临时缓存的远程Observable [英] RxJava pattern for requesting a remote Observable with a temporary cache

查看:109
本文介绍了RxJava模式,用于请求具有临时缓存的远程Observable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The use case is this: I want to temporarily cache the latest emitted expensive Observable response, but after it expires, return to the expensive source Observable and cache it again, etc.

一个非常基本的网络缓存方案,但我真的很难让它运行起来。

A pretty basic network cache scenario, but I'm really struggling to get it working.

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);
}

初始请求:转到源
第二次请求在30秒内source emit:从缓存中传递
缓存到期窗口之外的第三个请求:什么都没有。我订阅它并且我没有获得数据,但它没有切换到上游源Observable。

Initial request: goes to source Second request within 30 seconds of source emitting: delivered from cache Third request outside of cache expiry window: nothing. I subscribe to it and I get no data, but it's not switching to the upstream source Observable.

看起来好像我只是从<$连接到我的ConnectableObservable c $ c> autoConnect()并且它永远不会用空填充,因此它永远不会触发我的 switchIfEmpty()

It looks as if I'm just connecting to my ConnectableObservable from autoConnect() and it's never completing with empty, so it's never triggering my switchIfEmpty().

如何使用重播(1,x,x) switchIfEmpty()

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

Or am I just approaching this wrong from the start?

推荐答案

事实证明,即使在处置完毕后你也可以使用Jake Wharton的重播份额来缓存最后一个值。
https://github.com/JakeWharton/RxReplayingShare

So it's turns out you can use Jake Wharton's replaying share to cache the last value even after dispose. https://github.com/JakeWharton/RxReplayingShare

这篇关于RxJava模式,用于请求具有临时缓存的远程Observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆