我想用 RxJs 实现 Time Expiry 缓存。这是“正常”缓存的示例:
//let this represents "heavy duty job"
var data = Rx.Observable.return(Math.random() * 1000).delay(2000);
//and we want to cache result
var cachedData = new Rx.AsyncSubject();
data.subscribe(cachedData);
cachedData.subscribe(function(data){
//after 2 seconds, result is here and data is cached
//next subscribe returns immediately data
cachedData.subscribe(function(data2){ /*this is "instant"*/ });
});
subscribe
第一次调用on时cachedData
,调用“heavy duty job”,2 秒后结果保存在cachedData
( AsyncSubject
) 中。任何其他后续subscribe
oncachedData
立即返回并保存结果(因此缓存实现)。
我想要实现的是在cachedData
有效的时间段内“调味”,当那个时间过去时,我想为新数据重新运行“繁重的工作”并再次缓存这个新的时间期等...
期望的行为:
//pseudo code
cachedData.youShouldExpireInXSeconds(10);
//let's assume that all code is sequential from here
//this is 1.st run
cachedData.subscribe(function (data) {
//this first subscription actually runs "heavy duty job", and
//after 2 seconds first result data is here
});
//this is 2.nd run, just after 1.st run finished
cachedData.subscribe(function (data) {
//this result is cached
});
//15 seconds later
// cacheData should expired
cachedData.subscribe(function (data) {
//i'm expecting same behaviour as it was 1.st run:
// - this runs new "heavy duty job"
// - and after 2 seconds we got new data result
});
//....
//etc
我是 Rx(Js) 的新手,无法弄清楚如何通过冷却来实现这个热可观察对象。