RxJS patterns lab
The reactive patterns that keep showing up in real Angular work: a cancelling typeahead, a self-cleaning poller, the three task-flattening strategies, a retry with exponential backoff and what shareReplay changes about a cold source. Each is wired to a live, interactive demo. Every source is the seeded synthetic book; there is no network here, only timers.
debounceTimedistinctUntilChangedswitchMap
debounce → distinct → switchMap
Type an account name. Short terms (≤ 2 chars) are answered slowly on purpose, so a quick follow-up keystroke out-races the request it supersedes. switchMap cancels the stale one, so the results you see always match the latest term.
Start typing to see results.
timer(0, interval) → switchMap
A poll fires immediately and then every 1.5s, switchMapping to a synthetic “live price”. The subscription is held with takeUntilDestroyed and torn down on stop or when you leave the page, so no interval is left running.
mergeMap vs concatMap vs exhaustMap
Four tasks are emitted at once, each resolving to its id after a fixed delay: #1@600ms #2@200ms #3@400ms #4@100ms. Fire each strategy and watch the order the results arrive in. That order is the whole lesson.
mergeMapAll at once · fastest finishes first
concatMapQueued · strict emission order
exhaustMapFirst wins · the rest are dropped
Retry with exponential backoff
A flaky source fails twice then succeeds. Built on RxJS's retry() with a timer-driven delay, retryWithBackoff resubscribes after 400ms, then 800ms (base × 2ⁿ⁻¹), surfacing each attempt below before it finally lands.
toSignal() interop
One 1Hz counter observable, surfaced two ways. The left cell uses the | async pipe; the right reads a signal made with toSignal(). Same source, same value, two consumption styles.
| asynctoSignal()0Hot vs cold observables, and when to shareReplay
A cold observable starts its producer once for every subscriber: subscribe twice to an HTTP call and it sends two requests. A hot one runs a single producer that every subscriber shares. shareReplay() is one way to turn a cold source into a hot one. The sources below are fakes that count each request and connection they make, so you can watch the difference instead of hunting for it in the network tab.
Sharing a single request
Both cards use the same fake GET, which answers after 800ms. The left card subscribes to it directly; the right pipes it through shareReplay({ bufferSize: 1, refCount: true }). Subscribe two consumers: the cold source sends two requests, the shared one sends one and both consumers get its response. Once the responses are in, add a late subscriber. The cold source sends a third request and the late consumer waits for it. The shared one sends nothing and hands the late consumer response #1 at once.
The request had already completed, so refCount played no part in that replay. shareReplay doesn't reset once its source completes, so it keeps handing the last value to every later subscriber. refCount only matters while the source is still running, which the next demo shows.
No sharing (cold)
- Requests sent
- 0
- Consumer A
- waiting
- Consumer B
- waiting
- Late subscriber
- not subscribed
shareReplay({ bufferSize: 1, refCount: true })
- Requests sent
- 0
- Consumer A
- waiting
- Consumer B
- waiting
- Late subscriber
- not subscribed
Requests sent: cold source 0, shared source 0.
refCount: when the last subscriber leaves
A live feed never completes. Both cards share the same kind of fake feed, which ticks once a second, through shareReplay with bufferSize: 1; only refCount differs. Subscribe, then unsubscribe. With refCount: true the connection closes as soon as the last subscriber leaves, and subscribing again opens a second connection. With refCount: false the connection stays open with no subscribers and keeps sending ticks, and subscribing again reuses the first connection.
That open connection is the leak to watch for when refCount is false on a stream that never ends. This page closes it with takeUntil when you reset or leave.
refCount: true
- Connections opened
- 0
- Connection
- closed
- Subscribers
- 0
- Ticks sent by the source
- 0
- Latest tick received
- none
refCount: false
- Connections opened
- 0
- Connection
- closed
- Subscribers
- 0
- Ticks sent by the source
- 0
- Latest tick received
- none
refCount true: connection closed, 0 opened. refCount false: connection closed, 0 opened.
View source: the counted fake sources and their tests
fakeRequest and fakeFeed are cold on purpose and report every request and connection. The tests pin the shareReplay behavior this section shows.
import { Observable, defer, map, timer } from 'rxjs';
/*
* Two fake sources for the hot vs cold demo. Both are cold, like nearly everything RxJS and
* Angular hand you: nothing runs until something subscribes, and each subscription gets its own
* run of the producer. That is exactly what makes the difference hard to see in a real app, where
* a second HTTP request only shows up in the network tab. So both of these report every time
* they start (and the feed, every time it stops), and the page puts those numbers on screen.
*
* Neither does any sharing itself. Sharing is the caller's choice, made with `share()` or
* `shareReplay()` on the way out:
*
* const quote$ = fakeRequest(800, (n) => n, onSend).pipe(
* shareReplay({ bufferSize: 1, refCount: true }),
* );
*/
/*
* A stand-in for `HttpClient.get`: on subscribe it "sends" a request, then emits one response
* after `latencyMs` and completes. `defer` is what makes it cold. Its factory runs once per
* subscriber, so two subscribers mean two requests, numbered in the order they were sent.
* Unsubscribing before the response lands cancels the timer, as it would cancel a real request.
*/
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)));
});
}
export interface FeedEvents {
opened(connectionNo: number): void;
closed(connectionNo: number): void;
}
/*
* A stand-in for a socket or server-sent events: a stream that never completes. Each subscriber
* opens its own connection, which ticks 0, 1, 2... every `intervalMs` until that subscriber
* leaves. The teardown is where `closed` fires, so the page can show when a connection is still
* open with nobody listening. That is the case `refCount` decides.
*/
export function fakeFeed(intervalMs: number, events: FeedEvents): Observable<number> {
let connections = 0;
return new Observable<number>((subscriber) => {
const connectionNo = ++connections;
events.opened(connectionNo);
const ticks = timer(0, intervalMs).subscribe(subscriber);
return () => {
ticks.unsubscribe();
events.closed(connectionNo);
};
});
}
View source: this section
Every button acts on both cards, so the operator is the only difference between them.
import {
ChangeDetectionStrategy,
Component,
DestroyRef,
computed,
inject,
signal,
type WritableSignal,
} from '@angular/core';
import { Observable, Subject, Subscription, shareReplay, takeUntil, tap } from 'rxjs';
import { Button, Card, SourceViewer } from '@foo/ui';
import { fakeFeed, fakeRequest } from '@foo/rxjs-patterns';
import { rxjsHotCold } from '../../../shared/snippets/rxjsHotCold.generated';
import { rxjsHotColdTemplate } from '../../../shared/snippets/rxjsHotColdTemplate.generated';
import { rxjsSharing } from '../../../shared/snippets/rxjsSharing.generated';
import { rxjsSharingSpec } from '../../../shared/snippets/rxjsSharingSpec.generated';
const LATENCY_MS = 800;
const TICK_MS = 1000;
type Consumer = 'a' | 'b' | 'late';
interface RequestCard {
readonly key: 'cold' | 'shared';
readonly label: string;
readonly requests: number;
readonly responses: Readonly<Record<Consumer, string | null>>;
}
interface FeedState {
readonly connections: number;
readonly open: boolean;
readonly subscribers: number;
readonly produced: number;
readonly latest: number | null;
}
interface FeedCard {
readonly refCount: boolean;
readonly state: WritableSignal<FeedState>;
readonly feed$: Observable<number>;
}
const noResponses = { a: null, b: null, late: null } as const;
const closedFeed: FeedState = {
connections: 0,
open: false,
subscribers: 0,
produced: 0,
latest: null,
};
/*
* /rxjs#hot-cold. Every button acts on both cards at once, so the only difference between them
* is the operator under test. The counters come from the fake sources themselves (they report
* each request and connection), not from the subscribers, so they show what the producer did.
*/
@Component({
selector: 'foo-hot-cold',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [Button, Card, SourceViewer],
templateUrl: './hot-cold.html',
styleUrl: './hot-cold.scss',
})
export class HotCold {
protected readonly sources = [rxjsSharing, rxjsSharingSpec];
protected readonly pageSources = [rxjsHotCold, rxjsHotColdTemplate];
protected readonly latencyMs = LATENCY_MS;
// ── Two subscribers, one request ────────────────────────────────────────────────────
protected readonly cold = signal<RequestCard>(this.requestCard('cold', 'No sharing (cold)'));
protected readonly shared = signal<RequestCard>(
this.requestCard('shared', 'shareReplay({ bufferSize: 1, refCount: true })'),
);
protected readonly requestCards = computed(() => [this.cold(), this.shared()]);
protected readonly requestStep = signal<'idle' | 'two' | 'late'>('idle');
// The late subscriber only makes the point once the first responses are in.
protected readonly canAddLate = computed(
() =>
this.requestStep() === 'two' &&
this.cold().responses.a !== null &&
this.shared().responses.a !== null,
);
private cold$!: Observable<string>;
private shared$!: Observable<string>;
private requestSubs = new Subscription();
// ── refCount: when the last subscriber leaves ───────────────────────────────────────
protected readonly feeds = signal<readonly FeedCard[]>([]);
protected readonly feedSubscribed = signal(false);
private feedSubs = new Subscription();
/*
* With refCount: false, unsubscribing never reaches the source; that's the behavior on show.
* So the demo ends its feeds itself, upstream of shareReplay, when you reset or leave the page.
*/
private readonly stopFeeds$ = new Subject<void>();
constructor() {
this.resetRequests();
this.resetFeeds();
inject(DestroyRef).onDestroy(() => {
this.requestSubs.unsubscribe();
this.feedSubs.unsubscribe();
this.stopFeeds$.next();
});
}
protected subscribeTwo(): void {
this.requestStep.set('two');
for (const consumer of ['a', 'b'] as const) {
this.consume(this.cold$, this.cold, consumer);
this.consume(this.shared$, this.shared, consumer);
}
}
protected addLate(): void {
this.requestStep.set('late');
this.consume(this.cold$, this.cold, 'late');
this.consume(this.shared$, this.shared, 'late');
}
protected resetRequests(): void {
this.requestSubs.unsubscribe();
this.requestSubs = new Subscription();
this.requestStep.set('idle');
this.cold.set(this.requestCard('cold', this.cold().label));
this.shared.set(this.requestCard('shared', this.shared().label));
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 }),
);
}
protected subscribeFeeds(): void {
this.feedSubscribed.set(true);
for (const { state, feed$ } of this.feeds()) {
state.update((s) => ({ ...s, subscribers: s.subscribers + 1 }));
this.feedSubs.add(feed$.subscribe((tick) => state.update((s) => ({ ...s, latest: tick }))));
}
}
protected unsubscribeFeeds(): void {
this.feedSubscribed.set(false);
this.feedSubs.unsubscribe();
this.feedSubs = new Subscription();
for (const { state } of this.feeds()) {
state.update((s) => ({ ...s, subscribers: 0 }));
}
}
protected resetFeeds(): void {
this.unsubscribeFeeds();
this.stopFeeds$.next();
this.feeds.set([this.feedCard(true), this.feedCard(false)]);
}
private feedCard(refCount: boolean): FeedCard {
const state = signal<FeedState>(closedFeed);
const feed$ = fakeFeed(TICK_MS, {
opened: (n) => state.update((s) => ({ ...s, connections: n, open: true })),
closed: () => state.update((s) => ({ ...s, open: false })),
}).pipe(
// Counted before the share, so it shows ticks the source sends whether or not anyone listens.
tap(() => state.update((s) => ({ ...s, produced: s.produced + 1 }))),
takeUntil(this.stopFeeds$),
shareReplay({ bufferSize: 1, refCount }),
);
return { refCount, state, feed$ };
}
private consume(
source$: Observable<string>,
card: WritableSignal<RequestCard>,
consumer: Consumer,
): void {
this.requestSubs.add(
source$.subscribe((response) =>
card.update((c) => ({ ...c, responses: { ...c.responses, [consumer]: response } })),
),
);
}
private countRequest(card: WritableSignal<RequestCard>): void {
card.update((c) => ({ ...c, requests: c.requests + 1 }));
}
private requestCard(key: RequestCard['key'], label: string): RequestCard {
return { key, label, requests: 0, responses: noResponses };
}
}
The operators behind the demos
Every tab above is driven by the same handful of reusable operator pipelines: typeahead, poll, runWithStrategy and retryWithBackoff. Here is the source they share.
View sourcepatterns.ts
import {
Observable,
OperatorFunction,
concatMap,
debounceTime,
distinctUntilChanged,
exhaustMap,
from,
mergeMap,
retry,
switchMap,
timer,
toArray,
} from 'rxjs';
/*
* The RxJS patterns that turn up over and over in real Angular work: a typeahead, a poller,
* the three ways to flatten a stream of async tasks and a retry with backoff. Each one is the
* same lesson: the operators you choose encode a *policy* (cancel vs. queue vs. ignore, wait
* vs. retry), and picking the wrong one is a class of bug you can't see in a quick read.
*
* They take their side effects as function arguments rather than reaching for `http` directly.
* That keeps them pure and composable, and because every delay runs through `timer`, it lets
* a `TestScheduler` drive the whole thing in virtual time, so the tests are fast and deterministic
* instead of littered with real `setTimeout`s and flaky waits.
*/
/*
* A typeahead is a race, and switchMap is how you win it. Every keystroke starts a new search;
* switchMap cancels the one still in flight, so a slow early request can never land after a
* faster later one and overwrite the results you're looking at. debounceTime keeps us off the
* backend on every keystroke; distinctUntilChanged drops no-op repeats (an arrow key, a paste of
* the same text). The three together are the whole pattern. Remove any one and you get either a
* hammered backend, redundant requests or results that flicker to a stale answer.
*
* typeahead(term$, (q) => http.get(...)).subscribe(render);
*/
export function typeahead<T>(
term$: Observable<string>,
search: (term: string) => Observable<T>,
debounceMs = 250,
): Observable<T> {
return term$.pipe(
debounceTime(debounceMs),
distinctUntilChanged(),
switchMap((term) => search(term)),
);
}
/*
* Polling, done so it can't trip over itself. `timer(0, intervalMs)` fires once right away
* (no awkward blank first interval) and then on every tick. `switchMap` is the safety valve:
* if a fetch is still running when the next tick arrives, it's abandoned rather than allowed to
* stack up, so a backend slower than your interval gives you a backlog of one, not an
* ever-growing pile of overlapping requests.
*
* There's no stop button by design. The stream polls exactly as long as something is subscribed,
* so "stop" is just "unsubscribe." Pipe it through `takeUntilDestroyed()` in a component and the
* polling ends when the component does, with no teardown code to remember.
*/
export function poll<T>(intervalMs: number, fetch: () => Observable<T>): Observable<T> {
return timer(0, intervalMs).pipe(switchMap(() => fetch()));
}
/*
* One unit of fake async work: resolves to its `id` after `delayMs`. The delay is the variable
* that makes the strategies below visibly differ.
*/
export interface SimTask {
readonly id: number;
readonly delayMs: number;
}
export type ConcurrencyStrategy = 'merge' | 'concat' | 'exhaust';
/*
* Turns a task into the observable that emits its id once the delay elapses: the async unit the
* flattening operators below schedule against each other.
*/
function runTask(task: SimTask): Observable<number> {
return timer(task.delayMs).pipe(switchMap(() => from([task.id])));
}
/*
* The four "higher-order" operators (mergeMap, concatMap, exhaustMap and switchMap above)
* all answer the same question, "a new inner observable arrived while the last one is still
* going; what now?", and they answer it differently. People reach for mergeMap by reflex and
* inherit bugs they never chose. This runs the *same* tasks through three of them and returns the
* order results come back, because that arrival order IS the difference, made visible:
*
* - `merge`: start everything at once, let results race in; order follows each task's delay,
* not the order they were kicked off. Maximum concurrency, no ordering guarantee.
* - `concat`: queue them and run strictly one at a time; results always arrive in emission
* order, however slow each is. Ordered, but a slow early task blocks the rest.
* - `exhaust`: the first one wins; anything emitted while it's still running is dropped on the
* floor. This is the double-submit guard: ignore new clicks until the save lands.
*
* The choice is a policy decision: parallel-and-unordered, serialized-and-ordered, or
* ignore-while-busy. Returns the id array as an observable so a marble test can assert the order.
*/
export function runWithStrategy(
tasks: readonly SimTask[],
strategy: ConcurrencyStrategy,
): Observable<number[]> {
/*
* Same `runTask`, same input list; only the flattening operator changes. That's deliberate:
* hold everything else constant and the operator is the sole variable explaining the output.
*/
const operator: OperatorFunction<SimTask, number> =
strategy === 'merge'
? mergeMap((t) => runTask(t))
: strategy === 'concat'
? concatMap((t) => runTask(t))
: exhaustMap((t) => runTask(t));
return from(tasks).pipe(operator, toArray());
}
/*
* Retrying is easy; retrying *politely* is the part people skip. A flat retry loop hammers a
* struggling backend at full speed and helps push it over. Exponential backoff spaces the
* attempts out (wait `baseMs`, then 2x, then 4x), so a service having a bad moment gets room to
* recover instead of a stampede. On the nth retry (1-based) it waits `baseMs * 2^(n-1)`.
*
* The second half that matters: once `maxRetries` is spent, `retry` lets the error through. You
* want failure to eventually surface, not be swallowed into an infinite quiet retry loop the user
* can never escape. Use it as a pipeable operator:
*
* source$.pipe(retryWithBackoff(3, 200))
*
* Every delay is a `timer`, so a `TestScheduler` runs the entire backoff sequence in virtual time.
* The test asserts the whole escalation in microseconds, with no real waiting and no flake.
*/
export function retryWithBackoff<T>(maxRetries = 3, baseMs = 300): OperatorFunction<T, T> {
return retry<T>({
count: maxRetries,
delay: (_error, retryCount) => timer(baseMs * 2 ** (retryCount - 1)),
});
}