Learning about using the reactive pattern to cache streams
What you will be glad to find is that RxJS ships with a very useful operator to put in place a caching mechanism for streams, which is 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:
export class RecipesService { recipes$ = this.http.get<Recipe[]>(`${BASE_PATH}/recipes`); }
This means that the stream...