paint-brush
Sharing Observables: Preventing Identical Http Calls by@msarica
412 reads
412 reads

Sharing Observables: Preventing Identical Http Calls

by MehmetJanuary 27th, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

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.

Company Mentioned

Mention Thumbnail
featured image - Sharing Observables: Preventing Identical Http Calls
Mehmet HackerNoon 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.
... 
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 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:

demo: 

바카라사이트 바카라사이트 온라인바카라