Sub topic 13
Cold vs Hot Observables and Sharing with shareReplay
This chapter assumes you know how observables and subscriptions work, how HttpClient returns observables, and how a Subject pushes values to many subscribers.
Cold observables: one producer per subscriber
A cold observable creates its producer inside the subscribe call. Each subscriber gets its own execution. HttpClient.get works this way, so two subscriptions send two HTTP requests.
import { Observable } from 'rxjs';
const cold$ = new Observable<number>(subscriber => {
console.log('producer started');
subscriber.next(Math.random());
subscriber.complete();
});
cold$.subscribe(v => console.log('A', v));
cold$.subscribe(v => console.log('B', v));
// "producer started" is logged twice, and A and B receive different numbersHot observables: one producer shared by all
A hot observable's producer exists apart from any single subscriber. DOM events from fromEvent, a Subject, and router events are all hot. A subscriber that arrives late misses any values that were emitted before it subscribed.
| Aspect | Cold | Hot |
|---|---|---|
| Producer created | On each subscribe | Once, outside subscribers |
| Subscribers share values | No | Yes |
| Late subscribers | Get the full sequence | Miss earlier values |
| Angular examples | `HttpClient`, `of`, `interval` | `Subject`, `fromEvent`, router events |
Making a cold observable shared
The shareReplay operator turns a cold source into a shared one. It subscribes to the source once, multicasts each value through an internal ReplaySubject, and replays the last bufferSize values to late subscribers.
import { Observable, shareReplay } from 'rxjs';
const shared$ = new Observable<number>(subscriber => {
console.log('producer started');
subscriber.next(Math.random());
subscriber.complete();
}).pipe(shareReplay({ bufferSize: 1, refCount: true }));
shared$.subscribe(v => console.log('A', v));
shared$.subscribe(v => console.log('B', v));
// "producer started" is logged once, and A and B receive the same numberIn an Angular service, this pattern caches a request that many components need:
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { shareReplay } from 'rxjs';
interface AppConfig {
apiVersion: string;
}
@Injectable({ providedIn: 'root' })
export class ConfigService {
private http = inject(HttpClient);
readonly config$ = this.http
.get<AppConfig>('/api/config')
.pipe(shareReplay({ bufferSize: 1, refCount: true }));
}Because the service is a root singleton, every component that reads config$ reuses the same request.
Common errors
- Omitting
refCount.shareReplay(1)defaults torefCount: false. With that default, the source subscription stays open after every subscriber leaves. For a completing HTTP call this does no harm. For a long-lived source such asintervalor a WebSocket, it leaks. PassrefCount: truefor sources that never complete. - Expecting
refCount: trueto refetch. After the source completes, the cached value is kept even when the subscriber count drops to zero. To get fresh data, build a new observable or trigger a refetch from aSubject. - Assuming errors are cached. If the source errors,
shareReplayresets, and the next subscriber subscribes to the source again. This can fire repeated requests if many components subscribe after a failure. - Using
share()when late subscribers need the value.share()multicasts but replays nothing. A subscriber that joins after the HTTP response arrives gets nothing, or it triggers a new request once the shared subscription has reset. - Putting
shareReplayinside a method.getConfig() { return this.http.get(...).pipe(shareReplay(1)); }creates a new shared observable on every call, so nothing is shared. Store the piped observable in a field instead.
Exercise
A component template uses config$ | async in three places, and the Network tab shows three requests to /api/config. ConfigService defines getConfig() that returns this.http.get('/api/config').pipe(shareReplay(1)), and the component assigns config$ = this.configService.getConfig(). Why are there three requests, and how do you fix it?
Show answer
The method itself is called only once, so the problem is elsewhere. More likely, the component (or other components) calls getConfig() more than once, and each call builds a new shareReplay instance. If the three async pipes all read the same component field, they share one request. The reliable fix is to define readonly config$ = this.http.get(...).pipe(shareReplay({ bufferSize: 1, refCount: true })) as a field on the root-provided service, so every caller reads the same shared instance.
Exercise
You wrap interval(1000) in shareReplay(1) and subscribe from a component that is later destroyed. Does the interval keep running? What change stops it?
Show answer
Yes. With the default refCount: false, shareReplay keeps its subscription to interval alive after all subscribers unsubscribe. Use shareReplay({ bufferSize: 1, refCount: true }) so the source is unsubscribed when the subscriber count drops to zero.