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

app.module.ts:

app.component.ts:

app.component.html

app.component.html

app.service.ts

Link for whole code : Github

Link to check the output : Stackblitz

Originally published at

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store