Using the Reactive Pattern to Cache Streams
Explore the use of reactive patterns to cache streams.
We'll cover the following
RxJS ships with a very useful operator to put in place a caching mechanism for streams, which is the shareReplay
operator.
The shareReplay
operator
The shareReplay
operator shares an observable execution with multiple subscribers. It has an optional parameter, which is bufferSize
. Now, bufferSize
represents the number of emissions that are cached and replayed for every subscriber. In our case, we only need to replay the most recent value; hence, we need to set the bufferSize
parameter to 1
.
In a nutshell, the shareReplay
operator does the following:
Shares an observable execution with multiple subscribers.
Offers the possibility to replay a specified number of emissions to the subscribers.
Our recipes$
stream defined in RecipesService
is initially a cold stream.
Get hands-on with 1400+ tech skills courses.