Sharing Observables: Preventing Identical Http Calls

Written by msarica | Published 2020/01/27
Tech Story Tags: rxjs | angular | ionic | typescript | programming | javascript | web-components | angular-development

TLDR Share is an rxjs operator that you can easily implement using. It prevents multiple identical requests in the Network tab. The result is 6 identical API calls in a project that has multiple components that need the same resource. An easy solution is to share observables. You can create a variable to keep a reference to the ongoing request. Make a request and share it so that this can become a multicast observable. Also make sure to remove the reference once we get a response from the request. This will not cache the value.via the TL;DR App

Assume the following case: You have an Angular/Ionic project that has multiple components that need the same resource. When the app loaded, the components will start getting the fresh data from the backend. Hence you will probably see multiple identical calls in the Network tab.
I created a mock up project to simulate the issue. I created 3 components which are almost identical and placed them twice in the parent component. When they are initialized, they try to get books array from the back end.
... 
getBooks(){
    return this.http.get('getbooksUrl');
}
...
The result is 6 identical api calls.
One easy solution is to share observables. Share is an rxjs operator that you can easily implement.
  private _ongoingObservable;
  
  getBooks(){
    if(this._ongoingObservable){
      console.log('shared obs')
      return this._ongoingObservable;
    }
    
    this._ongoingObservable = this.http.get('someurl')
    .pipe(
      share(), 
      finalize(()=>{
        this._ongoingObservable = null;
      }));

    console.log('first time');
    return this._ongoingObservable;
  }
What we do here is quite simple. We created a variable to keep a reference to the ongoing request. In the method, we first check if it has a value, if it has return it. If not, that means there is not an active request. Make a request and share it so that this can become a multicast observable. Also make sure to remove the reference once we get a response from the request. Hence, we clear the variable in finalize operator.
This will not cache the value, it will only prevent multiple identical requests.
Here is the result:

Written by msarica | msarica.com
Published by HackerNoon on 2020/01/27