Sobes.tech
Middle

RxJS task: there is an Observable subscribed to three times in a template. How to make a single subscription instead of three, without directly using the async pipe? How do Subject and BehaviorSubject differ from a regular Observable (hot vs cold stream)?

sobes.tech AI

Answer from AI

If an Angular template subscribes three times to the same Observable, it can lead to three executions of the data source, which is inefficient. To make a single subscription instead of three, you can use the shareReplay operator or create a Subject/BehaviorSubject that will multicast the values.

Example with shareReplay:

const source$ = this.http.get('/api/data').pipe(
  shareReplay(1) // caches the last emitted value and shares it with subscribers
);

Now, multiple subscribers will receive the same value without repeated requests.

If you do not use the async pipe, you can subscribe once in the component and pass the data to the template via a variable.


Differences between Subject and BehaviorSubject from a regular Observable:

  • Observable — cold stream: the data source restarts for each subscriber.
  • Subject — hot stream: multicasts values to all subscribers, the source starts once.
  • BehaviorSubject — a Subject that stores the current value. It immediately emits the last value upon subscription, even if the subscriber came later.

Thus, Subject and BehaviorSubject allow sharing a single data source among multiple subscribers without restarting the source.

RxJS task: there is an Observable subscribed to three… - sobes.tech