Posts

Showing posts with the label shareReplay

Avoiding multiple API calls in Angular by using shareReplay method of RxJS

Image
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 share...