RxJS - How to make observable stream trigger only on first subscription

Viewed 705

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?

2 Answers

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$;
  }
Related