Sharing Observables: Preventing Identical Http Calls

Author profile picture


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.
    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;
      console.log('shared obs')
      return this._ongoingObservable;
    this._ongoingObservable = this.http.get('someurl')
        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:


The Noonification banner

Subscribe to get your daily round-up of top tech stories!