How to correctly retrieve and cache data in Angular service

后端 未结 3 1853
南旧
南旧 2021-01-29 02:29

Frequently, in angular app, i have some service, which need to retreive some data through http request and share it to consumers through BehaviorSubject. It have implementation

3条回答
  •  不知归路
    2021-01-29 03:03

    The best way is using rxjs shareReplay. This operator returns an Observable that shares a single subscription to the underlying source. In other words, turns our observable hot.

    const CACHE_SIZE = 1;
    class Service { 
    
      private _data$: Observable;
    
      get data(): Observable {
        if (!this._data$) {
          this._data$ = anyHttpCall()
            .pipe(shareReplay({ refCount: true, bufferSize: CACHE_SIZE })
          );
        }
        return this._data$;
      }
    }
    

    The bufferSize determines the maximum element count of the replay buffer, that is the number of elements that are cached and replayed for every subscriber.

    This post explains this very good: https://blog.thoughtram.io/angular/2018/03/05/advanced-caching-with-rxjs.html

提交回复
热议问题