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
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