是否有一种安全的方法可以推迟创建Observable<T>
,但是在创建缓存之前,它必须再次创建它?
Observable.cachedDefer(() -> createExpensiveFiniteObservable().cache(), 5, TimeUnit.MINUTES);
我有构建成本高昂的数据集,我希望它们的缓存时间足以支持进程,但让它们在每次运行之间大致到期。
答案 0 :(得分:1)
我已将此功能添加到 rxjava-extras 。下面的代码取决于 rxjava-extras 0.6.8-RC2或更高版本(在Maven Central上)。
运行下面的main
方法,您会看到这些结果似乎与您想要的行为相匹配(每当下次订阅的时间间隔为&gt; = 5秒时重置缓存):
source emits Tue Oct 13 21:00:16 AEDT 2015
Tue Oct 13 21:00:16 AEDT 2015
Tue Oct 13 21:00:16 AEDT 2015
Tue Oct 13 21:00:16 AEDT 2015
Tue Oct 13 21:00:16 AEDT 2015
Tue Oct 13 21:00:16 AEDT 2015
source emits Tue Oct 13 21:00:31 AEDT 2015
Tue Oct 13 21:00:31 AEDT 2015
Tue Oct 13 21:00:31 AEDT 2015
Tue Oct 13 21:00:31 AEDT 2015
Tue Oct 13 21:00:31 AEDT 2015
Tue Oct 13 21:00:31 AEDT 2015
source emits Tue Oct 13 21:00:46 AEDT 2015
Tue Oct 13 21:00:46 AEDT 2015
Tue Oct 13 21:00:46 AEDT 2015
...
主要方法:
public static void main(String[] args) throws InterruptedException {
Observable<Date> source = Observable
.defer(() ->
Observable
.just(new Date())
.doOnNext(
d -> System.out.println("source emits " + d)));
CloseableObservableWithReset<Date> cached =
Obs.cache(source, 5, TimeUnit.SECONDS, Schedulers.computation());
Observable<Date> o = cached
.observable()
.doOnSubscribe(() -> cached.reset());
for (int i = 0; i < 30; i++) {
o.doOnNext(System.out::println).subscribe();
Thread.sleep((i % 5 + 1)*1000);
}
cached.close();
}
请注意,要重置每个发射的缓存以及您看到的位置
.doOnSubscribe(() -> cached.reset())
把
.doOnSubscribe(() -> cached.reset())
.doOnNext(x -> cached.reset())