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
What about your options:
1) Should work but as for me it requires a lot of code written by hand.
2) Imagine user won't call getData
method but you have already sent redundant request.
There is a very convenient operator shareReplay
that will help you make your cold observable hot.
import { Observable } from 'rxjs';
import { shareReplay } from 'rxjs/operators';
export class Service {
private cache$: Observable;
...
getData() {
if (!this.cache$) {
this.cache$ = this.anyHttpCall().pipe(
shareReplay(1)
);
}
return this.cache$;
}
}
Ng-run Example