本文介绍了RxJava- cache()与replay()相同吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一个 cache()运算符可以缓存x个数量的排放,但也会在指定的时间间隔(例如1分钟)后过期。我正在寻找类似的东西......

I was wondering if there was a cache() operator that could cache x number of emissions but also expire them after a specified time interval (e.g. 1 minute). I was looking for something like...

Observable<ImmutableList<MyType>> cachedList = otherObservable
    .cache(1, 1, TimeUnit.MINUTES); 

这会缓存一个项目,但会在一分钟后过期并清除缓存。

This would cache one item but would expire and clear the cache after a minute.

我做了一些研究,找到了操作员。看起来它可以满足这种需求,但我有一些问题。为什么它很热并且需要连接?这是否与 cache()运算符不同?我知道 cache()模仿主题,但不需要连接。

I did some research and found the replay operator. It seemed like it would fulfill this need but I have some questions. Why is it hot and needs to be connected? Does this make it different than the cache() operator? I know the cache() mimics a subject, but it does not require being connected.

推荐答案

缓存重播适用于不同的用例。缓存是一种自动连接重放 - 通常用于长期重放的所有容器。重放可以有更多的参数化,可以进行有限的时间/大小重放,但需要开发人员指定何时开始。 autoConnect()运算符允许您将此 ConnectableObservable 实例转换为普通 Observable 一旦订阅者订阅它们就连接到源。通过这种方式,您可以进行有界和自动连接重播(需要RxJava 1.0.14 +):

cache and replay are meant for different use cases. Cache is an auto-connecting replay-everything container used typically for long-term replays. Replay can have more parametrization and can do bounded time/size replays but requires the developer to specify when to start. The autoConnect() operator lets you turn such ConnectableObservable instances to a plain Observable which connects to the source once a subscriber subscribes to them. This way, you can have a bounded and auto-connecting replay (requires RxJava 1.0.14+):

source.replay(1, TimeUnit.SECONDS).autoConnect().subscribe(...);

这篇关于RxJava- cache()与replay()相同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 16:27