Sub topic 13
Cold vs Hot Observables and Sharing with shareReplay
This chapter assumes you already know how to subscribe to observables, how HttpClient returns observables, and how Subject and ReplaySubject work. It explains why some observables do their work again for every subscriber while others don't, and how to control that behavior with share and shareReplay.
The Working Model: Where the Producer Lives
Every observable has a producer, which is the thing that actually generates values. Examples are an HTTP request, a timer, or a DOM event listener. Whether an observable is cold or hot depends on where that producer lives.
- A cold observable creates its producer inside the subscribe call. Each subscriber gets its own producer and its own independent sequence of values.
- A hot observable uses a producer that exists outside any single subscription. All subscribers share it. A subscriber that joins late misses whatever was emitted before it arrived.
| Property | Cold | Hot |
|---|---|---|
| Producer created | Once per subscription | Once, shared by all |
| Late subscriber sees | The full sequence from the start | Only values emitted after it subscribes |
| Typical examples | `HttpClient.get`, `of`, `interval`, `defer` | `Subject`, `fromEvent` on a shared element, router events |
| Side effects | Repeated for each subscriber | Happen once |
Most RxJS creation functions and all HttpClient methods return cold observables. That is a safe default, but it causes trouble when several parts of the UI subscribe to the same request.
Seeing Cold Behavior
The script below uses defer to simulate an HTTP call and count how many times the producer runs. It runs in Node with only rxjs installed.
import { defer, of, delay } from 'rxjs';
let calls = 0;
const fakeRequest$ = defer(() => {
calls++;
console.log(`request #${calls} sent`);
return of({ apiVersion: 'v2' }).pipe(delay(100));
});
fakeRequest$.subscribe(v => console.log('A received', v));
fakeRequest$.subscribe(v => console.log('B received', v));
// Output:
// request #1 sent
// request #2 sent
// A received { apiVersion: 'v2' }
// B received { apiVersion: 'v2' }Two subscribers caused two requests. In Angular this usually shows up when a template uses the same HTTP observable twice:
import { Component, inject } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { HttpClient } from '@angular/common/http';
interface Profile {
name: string;
email: string;
}
@Component({
selector: 'app-profile',
standalone: true,
imports: [AsyncPipe],
template: `
<h2>{{ (profile$ | async)?.name }}</h2>
<p>{{ (profile$ | async)?.email }}</p>
`,
})
export class ProfileComponent {
private http = inject(HttpClient);
profile$ = this.http.get<Profile>('/api/profile');
}Each async pipe subscribes separately, so the browser's network tab shows two identical GET /api/profile requests. For a template that uses the value in one place only, the usual fix is a single @if (profile$ | async; as profile) block. When the subscribers are in different components or services, you need multicasting instead.
Multicasting: Turning Cold into Hot
Multicasting means putting a Subject between the source and the subscribers. The Subject subscribes to the source once and passes every notification on to all of its own subscribers. RxJS gives you two operators for this.
share()connects through a plainSubject. Subscribers who arrive while the source is active share it. Late subscribers get nothing that was already emitted.shareReplay()connects through aReplaySubject. Late subscribers receive the buffered values immediately.
Here is the earlier script with sharing added, plus a late subscriber:
import { defer, of, delay, share, shareReplay } from 'rxjs';
function makeRequest(label: string) {
let calls = 0;
return defer(() => {
calls++;
console.log(`${label}: request #${calls} sent`);
return of({ apiVersion: 'v2' }).pipe(delay(100));
});
}
const withShare$ = makeRequest('share').pipe(share());
const withReplay$ = makeRequest('shareReplay').pipe(
shareReplay({ bufferSize: 1, refCount: true })
);
for (const [name, obs$] of [['share', withShare$], ['shareReplay', withReplay$]] as const) {
obs$.subscribe(v => console.log(`${name} A`, v));
obs$.subscribe(v => console.log(`${name} B`, v));
setTimeout(() => obs$.subscribe(v => console.log(`${name} late`, v)), 500);
}Both operators send one request for A and B. The late subscriber is where they differ. share() resets once the source completes, so the late subscriber starts a second request. shareReplay keeps the completed ReplaySubject and replays the cached value without sending a new request.
Using shareReplay in an Angular Service
The usual place for shareReplay is a field on a root service, so every consumer reads the same cached result:
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 }));
}Any component can inject ConfigService and use config$ with the async pipe or toSignal. The request runs once for the lifetime of the application.
How shareReplay Works Internally
In RxJS 7, shareReplay(config) is a thin wrapper over share with these settings:
| share option | Value used by shareReplay | Effect |
|---|---|---|
| `connector` | `() => new ReplaySubject(bufferSize, windowTime)` | Buffers the last `bufferSize` values |
| `resetOnError` | `true` | An error discards the cache, so the next subscriber retries the source |
| `resetOnComplete` | `false` | A completed source keeps its cache permanently |
| `resetOnRefCountZero` | the `refCount` option | Decides whether the source is unsubscribed when the last subscriber leaves |
This table explains most of the behavior you will see in practice. Failed requests are not cached. Successful HTTP responses are cached even with refCount: true, because the source completed before the subscriber count dropped to zero.
Common Errors and Gotchas
Forgetting refCount on long-lived sources
shareReplay(1) is shorthand for { bufferSize: 1, refCount: false }. With refCount: false, the inner subscription to the source stays open even after every subscriber has unsubscribed. HTTP requests complete on their own, so this makes no difference for them. For a source that never completes, it is a leak:
import { interval, tap, shareReplay } from 'rxjs';
const ticks$ = interval(1000).pipe(
tap(n => console.log('producer tick', n)),
shareReplay(1)
);
const sub = ticks$.subscribe();
setTimeout(() => sub.unsubscribe(), 2500);
// "producer tick" keeps logging forever.
// Change to shareReplay({ bufferSize: 1, refCount: true }) and it stops after tick 1.In an Angular service the same leak keeps WebSocket feeds, polling timers, or fromEvent listeners alive after every component that used them has been destroyed.
Creating the shared observable on every call
Sharing only happens when consumers subscribe to the same observable instance. The following method builds a new pipeline, with a new cache, on every call, so it caches nothing:
getConfig() {
return this.http.get<AppConfig>('/api/config').pipe(shareReplay(1));
}Assign the shared observable to a field once, as ConfigService does above.
Placing operators after shareReplay
Operators placed before shareReplay run once. Operators placed after it run separately for each subscriber. Put expensive map calls and tap side effects such as logging upstream of the share.
A cache that never expires
A completed shareReplay holds its value for as long as the service exists, which for a root service is the whole app session. If the data can go stale, pass windowTime (in milliseconds) so the buffered value expires, or rebuild the stream from a refresh trigger. The next chapter covers a fuller approach with a BehaviorSubject-backed state service.
Cancelled requests with refCount: true
If every subscriber leaves before the response arrives, refCount: true unsubscribes from the source and HttpClient aborts the request. The next subscriber sends a new one. This is usually what you want, but it can confuse you when you watch the network tab during fast navigation.
Choosing an Approach
| Situation | Use |
|---|---|
| One subscriber, or each subscriber should get fresh data | No sharing (leave it cold) |
| Several concurrent subscribers, late ones need nothing old | `share()` |
| Cache a one-time result such as config or reference data | `shareReplay({ bufferSize: 1, refCount: true })` |
| Share a never-ending feed and replay its latest value | `shareReplay({ bufferSize: 1, refCount: true })` |
| Cached value must expire | `shareReplay({ bufferSize: 1, windowTime: 60000, refCount: true })` |
Exercise
A service exposes prices$ = webSocketFeed$.pipe(shareReplay(1)). After users leave the prices page, the browser still receives WebSocket messages. Why, and what is the fix?
Show answer
shareReplay(1) defaults to refCount: false, so the operator stays subscribed to the never-completing WebSocket source after every subscriber has unsubscribed. Change it to shareReplay({ bufferSize: 1, refCount: true }) so the source is unsubscribed when the subscriber count drops to zero.
Exercise
users$ = http.get('/api/users').pipe(share()) is subscribed by a header component at startup and by a sidebar component that loads two seconds later. How many requests are sent, and how would shareReplay change that?
Show answer
Two requests. share() resets when the source completes, so the sidebar's later subscription starts a new request. With shareReplay({ bufferSize: 1, refCount: true }) only one request is sent, because the completed ReplaySubject is kept and replays the response to the sidebar.
Exercise
The first request through a shareReplay-cached config$ fails with a 500 error. A component subscribes again a moment later. Does it receive the cached error or trigger a new request?
Show answer
It triggers a new request. shareReplay uses resetOnError: true, so an error discards the ReplaySubject and the next subscriber resubscribes to the source.