Reputation: 170
I have an observable which, when subscribed to, triggers a chain/stream of logic. This observable can be subscribed to in multiple of my components, as I need its logic to be active in multiple places in my app. However, I do not want its logic to be triggered a second time if it has already been triggered (by being subscribed to) in the past. How may I do so?
In other words, how can I trigger my observable's stream only the first time it is subscribed to?
Upvotes: 1
Views: 2669
Reputation: 710
shareReplay(1) works fine when you get your result once and other further delayed calls needs same result. but when first call's answer is yet to come, other calls make new requests. here you can prevent this behavior:
private products$: observable<Product[]>;
get() {
if(!this.products$){
this.products$ = this.apiService.getProducts().pipe(shareReplay(1));
}
return this.products$;
}
Upvotes: 0
Reputation: 15305
I think shareReplay(1)
operator would do what you want: it will emit the last "computed" value on each subscription.
See documentation for reference: https://www.learnrxjs.io/learn-rxjs/operators/multicasting/sharereplay
Upvotes: 2