Table contents
Purpose
In our application, users often revisit the same path/page multiple times. Each time a user returns to the page, the application makes another API call. However, why do we call the same API path every time the user returns to the page instead of saving the request and reusing it?
Pros:
- Saving API resources (fewer calls, lower cost)
- Eliminating repetitive loaders every time the user enters the page
What?
To achieve this, we utilize the shareReplay
method in RxJS. According to the documentation, shareReplay
replays the result of an Observable as many times as needed.
How?
Implementing it is straightforward. All you need to do is add the shareReplay
pipe to the Observable, as shown in the code below:
public getFacts() {
return this.httpClient.get<Fact[]>('https://cat-fact.herokuapp.com/facts')
.pipe(shareReplay());
}
Now you're all set. Simply use the method, and the pipe will handle everything for you.
Seeing the change
Let's compare the difference between using shareReplay
and not using it.
Without using it:
Notice that every time I click "Call subscriber" my code makes an HTTP call and returns the cat facts.
However, since my API changes daily rather than constantly, let's add shareReplay and observe the result:
See? When I clicked "Call subscriber", it returned the same result without making any additional HTTP calls!
Conclusion
RxJS is a powerful tool, and with just a simple line of code, your performance could be significantly improved.
Cheers!!!
Top comments (2)
How to clear cache at certain time interval ?
In that case you can do the share method.
e.g:
We use the replaySubject as connector.
If api throws an error we reset it immediatly, otherwise we wait the timer subject to finish and resets it!
Regards