1

I have a scenario where I want to fetch some piece of data from a server, and where the user can request a refresh of this data. The rest of the page needs to update to reflect the currently loaded iteration of the data.

I am picturing this where I have a hot Observable that publishes the data that it loads. I don't want to retain all the old iterations of the data as 1. I only care about the latest iteration of the data and 2. it could lead to an out-of-memory exception if the user refreshes enough in a given session.

However, I DO want to retain the last published value so that if I dynamically bring up a new component that needs access to that same data, it isn't sending out a new request unnecessarily. For this I need an Observable to sit ontop of the hot observable which will only retain and emit the last emission from the hot observable. Here's a diagram illustrating this idea:

dataStream     X - - - - - Y - - - - |> 
echoStream     X - - - - - Y - - - - |> 
subscription1  X - - - - - Y - - - - |> 
subscription2          X - Y - - - - |> 
subscription3                  Y - - |>

echoStream is subscribed to the dataStream. The subscription1, subscription2, and subscription3 are all subscribed to echoStream, but they subscribe at different points. At the time of subscription they get the last value that was emitted from the dataStream, and receive subsequent updates from dataStream.

echoStream is a bit of a mix of a Hot and Cold Observable, having a limited history retention.

Does rxjs provide a standard operator for setting up something like echoStream in the above example?

4

1 回答 1

2

据我了解,您可以shareReplay以这种形式使用运算符:

echoStream = dataStream.shareReplay(1)

正如文档所说:

返回一个可观察的序列,该序列共享对基础序列的单个订阅并重播通知 [...]

该操作符是重放的一种特殊化,当观察者的数量从零变为一时连接到可连接的可观察序列,当没有更多的观察者时断开连接。

所以这个操作员在这里做了两件事。当订阅者订阅流时,它会立即接收流发出的最新值(或 n 个最新值或现在之前 Xms 时间窗口中发出的值 - 取决于您在调用运算符时传递的参数)。这就是回放功能。然后是自动取消订阅功能,当流不再有任何订阅者时,该功能就会启动。

如果您不关心自动取消订阅,您可以使用replay运算符,您将只获得重播功能。例如:

echoStream = dataStream.replay(1)

于 2016-03-16T19:14:25.943 回答