Avoiding multiple API calls in Angular by using shareReplay method of RxJS
While working with some Angular projects, we’ve to subscribe the same API in to different methods in a component. In order to avoid that we can use shareReplay method of RxJS.
Lets consider an app which has two buttons and two different methods gets called on clicking on those buttons. But, internally the two methods will subscribe the same API two times. Suppose user clicks the button multiple times, then we’ve to call the same API multiple times to display the number of completed/incomplete tasks.
On clicking the `Completed Todos` and `Incomplete Todos` buttons, same API got two times. This will increase the load on server and increase the loading time of UI. Henceforth, reduces the performance of our application.
We can avoid calling multiple API services with the help of shareReplay method of RxJS. shareReplay subscribes the observable, caches the response and multicasts it to all the subscribers without calling the API multiple times.
Lets see the above example with shareReplay. The only thing we’ve to do is include `shareReplay` method in the API call.
Now, if we clicked on both buttons, it’ll be called only once nevertheless of how many times you click the buttons only one time it gets called.
Here is the whole structure of the project
Link for whole code : Github
Link to check the output : Stackblitz
Originally published at