HTTP服务的响应式缓存 [英] Reactive Caching of HTTP Service
问题描述
我正在使用RsJS 5(5.0.1)在Angular 2中进行缓存.它运行良好.
I am using RsJS 5 (5.0.1) to cache in Angular 2. It works well.
缓存功能的实质是:
const observable = Observable.defer(
() => actualFn().do(() => this.console.log('CACHE MISS', cacheKey))
)
.publishReplay(1, this.RECACHE_INTERVAL)
.refCount().take(1)
.do(() => this.console.log('CACHE HIT', cacheKey));
actualFn
是this.http.get('/some/resource')
.
就像我说的那样,这很适合我.在RECACHE_INTERVAL
的持续时间内从可观察的对象返回缓存.如果在该间隔之后发出请求,则将调用actualFn()
.
Like I say, this is working perfectly for me. The cache is returned from the observable for duration of the RECACHE_INTERVAL
. If a request is made after that interval, the actualFn()
will be called.
我要弄清楚的是RECACHE_INTERVAL
到期并且actualFn()
被称为—的时间.如何返回最后一个值.在RECACHE_INTERVAL
到期和重播actualFn()
之间存在时间间隔,即可观察对象不返回值.我想摆脱时间上的空白,并始终返回最后一个值.
What I am trying to figure out is when the RECACHE_INTERVAL
expires and the actualFn()
is called — how to return the last value. There is a space of time between when the RECACHE_INTERVAL
expires and the actualFn()
is replayed that the observable doesn't return a value. I would like to get rid of that gap in time and always return the last value.
我可能会产生副作用,并在等待HTTP响应返回时存储最后一个具有价值的调用.next(lastValue)
,但这似乎很幼稚.我想使用"RxJS"方式,一种纯函数解决方案—如果可能的话.
I could use a side effect and store the last good value call .next(lastValue)
while waiting for the HTTP response to return, but this seems naive. I would like to use a "RxJS" way, a pure function solution — if possible.
推荐答案
如果使用普通的rxjs
,几乎所有复杂的逻辑都会很快失去控制.我宁愿从头开始实现自定义cache
运算符,您可以使用以下要点作为示例
Almost any complicated logic quickly goes out of control if you use plain rxjs
. I would rather implement custom cache
operator from scratch, you can use this gist as an example.
这篇关于HTTP服务的响应式缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!