Page loaded: Hot and Cold Observables, Shared on Purpose

Photo by Derek Liang on Unsplash

State & Reactivity

Hot and Cold Observables, Shared on Purpose

Sharing an observable is a decision about who gets the same run of its work and what happens when they leave. Write that decision out per stream, and leave the rest cold.

Miguel Carino
Focus
Front-end web architecture, Angular, team leadership, and stakeholder communication
Experience
25+ years turning enterprise web complexity into maintainable products
return this.http.get<Settings>('/api/settings').pipe(shareReplay(1));

That line, or one like it, sits at the end of a lot of Angular services. It reads like good hygiene: make the request once, then hand the answer to everyone who asks. Sometimes that's exactly what it does. Other times it keeps a response that should have been fetched again, or holds a connection open after the last screen that needed it has gone.

Angular, Google's framework for building web apps, does its HTTP work through RxJS, a library for streams of values over time. Each stream is an observable, and HttpClient.get() returns one that does nothing until something subscribes. In the words of Angular's HTTP guide, it "will make a new backend request for each subscription." A source that starts fresh for every subscriber is called cold. A hot source runs one producer, one request or one socket, and every subscriber shares it. shareReplay is the operator most people use to turn cold into hot, and shareReplay(1) is the shorthand that gets copied.

The difference is hard to see in a real app, where a second request is one more line in the network tab. So on my demo site, demo.miguelcarino.com, a public Angular app I keep as working proof for this blog, I built a hot vs cold section whose fake sources count every request and connection they make and put the counts on screen.

What the shorthand actually sets

shareReplay(1) means a buffer of one value and refCount: false. In RxJS's own source, shareReplay is a thin call to share(), the general sharing operator, with a few of its options fixed (trimmed to the return):

return share<T>({
  connector: () => new ReplaySubject(bufferSize, windowTime, scheduler),
  resetOnError: true,
  resetOnComplete: false,
  resetOnRefCountZero: refCount,
});

resetOnComplete: false means that once the request completes, its response stays in the buffer for every later subscriber, for as long as the observable exists. Put that observable in a service that lives as long as the app, and the first answer is the only answer. For settings that never change mid-session, that's the point. For a list that someone else can edit, it's a stale screen with no request behind it.

resetOnRefCountZero: refCount, with refCount false in the shorthand, means that when the last subscriber leaves a source that is still running, the subscription to the source stays. A finished request has nothing left running, so it doesn't matter there. On a stream that never ends, a socket or a polling timer, it's a leak.

And when only one thing ever subscribes, the operator buys nothing except a cache nobody asked for.

Two subscribers, one request

The first demo uses a stand-in for HttpClient.get, from the demo's shared RxJS library (trimmed):

import { Observable, defer, map, timer } from 'rxjs';

export function fakeRequest<T>(
  latencyMs: number,
  respond: (requestNo: number) => T,
  onSend: (requestNo: number) => void,
): Observable<T> {
  let sent = 0;
  return defer(() => {
    const requestNo = ++sent;
    onSend(requestNo);
    return timer(latencyMs).pipe(map(() => respond(requestNo)));
  });
}

defer runs its factory once per subscriber, which is what makes it cold. The page builds two copies, one left alone and one shared (trimmed from the section's component):

const respond = (n: number) => `response #${n}`;
this.cold$ = fakeRequest(LATENCY_MS, respond, () => this.countRequest(this.cold));
this.shared$ = fakeRequest(LATENCY_MS, respond, () => this.countRequest(this.shared)).pipe(
  shareReplay({ bufferSize: 1, refCount: true }),
);

Press "Subscribe two consumers" and the cold card sends two requests: consumer A gets response #1 and consumer B gets response #2. The shared card sends one, and both consumers get response #1.

Wait for the answers, then press "Add a late subscriber." The cold source sends a third request, and the late consumer waits 800 milliseconds for it. The shared source sends nothing and hands over response #1 at once. The status line ends at "Requests sent: cold source 3, shared source 1."

Notice that refCount: true didn't stop that replay. The request had completed, and shareReplay never resets on completion, so the buffer outlives every subscriber. That replay is the cache.

refCount on a stream that never ends

The second demo swaps the request for a fake live feed that ticks once a second and never completes. Both cards share it through shareReplay with a buffer of one. Only refCount differs.

Subscribe, then unsubscribe. With refCount: true, the connection closes the moment the last subscriber leaves, and subscribing again opens a second one. With refCount: false, the card shows zero subscribers and an open connection, and its "Ticks sent by the source" count keeps climbing. Subscribe again and it reuses the first connection.

It's the last person out of the office leaving the lights on. Nothing breaks, and the bill keeps coming. The section's component pipes each feed through takeUntil ahead of the share, so it can end them itself on reset or when you leave the page. That's the cleanup refCount: false leaves to you.

The config form helps here. Pass an object to shareReplay and TypeScript requires refCount, so the choice is written where the next reader will see it.

share(), signals or leaving it cold

share() on its own is the other half of the toolbox. Its defaults reset on error, on completion and when the subscriber count reaches zero, and it uses a plain Subject, so it replays nothing. Subscribers who arrive while a request is in flight join it, and anyone who arrives after it completes starts a new one. That dedupes the burst of components asking for the same thing on page load without keeping a stale copy. On a live feed, it means a late subscriber sees the next value instead of an old one.

In a component, much of the reason to share is the template. Two async pipes on one cold observable are two subscriptions, so two requests:

<h2>{{ (user$ | async)?.name }}</h2>
<p>{{ (user$ | async)?.email }}</p>

toSignal subscribes once and returns a signal, Angular's reactive value holder, that the template can read as often as it likes. It unsubscribes when the component is destroyed. Each call to toSignal is its own subscription, so the signal is the thing to share. httpResource, stable since Angular 22, goes a step further. It makes the request from signals, sends a new one when they change, cancels any request still pending and gives you its value, loading state and error as signals. For a component that just needs data, the signal does the sharing and the observable underneath can stay cold.

Sometimes cold is the right answer. One subscriber needs no sharing. A save should send a request every time it's subscribed, and one shared through shareReplay would hand the second click the first save's response. A search box wants each keystroke to be a fresh, cancelable request, which is the switchMap story in The Typeahead That Answered Out of Order.

Share a Stream Because Two Things Need It

Cold is the default for a reason: every subscriber gets its own run of the work. I only share a stream when several things subscribe to it at the same time. If its answer can be reused, that's shareReplay({ bufferSize: 1, refCount: true }), with the config written out. If each subscriber should get a fresh answer, it's share(). In a component, I let a signal do the sharing. Anything else stays cold.