Skip to content

RxJS in Angular

Signals changed what RxJS is for in Angular, and a lot of existing code has not caught up. Streams that only ever held a current value are now signals. But a whole category of problems — anything involving time, cancellation, or coordination between events — has no signal answer, and reaching for signals there produces worse code than the observable it replaced.

The useful framing: signals model state, observables model events over time. Most of the confusion comes from code that used observables to model state because that was the only reactive primitive available.

Problem Why signals do not solve it
Debouncing and throttling Signals have no concept of time
Cancelling a superseded request switchMap has no signal equivalent
Retry with backoff Needs a scheduler
Coordinating several sources combineLatest, forkJoin, zip, race
A stream of discrete events Signals coalesce; three writes emit once
Backpressure Signals do not queue
Long-lived subscriptions to external sources WebSockets, event streams

That last row about coalescing is the one that surprises people. Signals never notify synchronously and never emit intermediate values:

mySignal.set(1);
mySignal.set(2);
mySignal.set(3);
// A subscriber to toObservable(mySignal) sees only 3.

For rendering that is a feature. For an event log, an analytics stream, or anything that must observe every occurrence, it is data loss — and the source of truth needs to be a Subject, not a signal.

Component state that used to be a BehaviorSubject should now be a signal. Derived values that used to be map over a subject should be computed. Async data with loading and error states should be httpResource or resource.

// Before
private readonly filter$ = new BehaviorSubject('');
readonly visible$ = combineLatest([this.orders$, this.filter$]).pipe(
map(([orders, filter]) => orders.filter((o) => o.customer.includes(filter))),
);
// After
readonly filter = signal('');
readonly visible = computed(() =>
this.orders().filter((o) => o.customer.includes(this.filter())),
);

The second version is synchronous to read, needs no subscription, no initialValue, no AsyncPipe, and is testable without a marble diagram. That is the case for the migration, and it is a strong one wherever the value is genuinely state.

The pragmatic rule: RxJS in the middle, signals at the edges. Time-based orchestration with operators; hand a signal to the template.

You do not need all of RxJS. In an Angular application, this handful covers most of it.

Choosing wrongly here is the most consequential RxJS mistake in Angular applications.

Operator On a new outer value Use for
switchMap Cancels the previous inner observable Search, navigation-driven loads — anything superseded
concatMap Queues; runs in order Ordered writes that must all happen
mergeMap Runs concurrently Independent parallel work
exhaustMap Ignores new values while one is running Submit buttons — prevents double submission
readonly results$ = this.query$.pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap((q) => this.http.get<Result[]>(`/api/search?q=${q}`)),
);

switchMap here is not an optimisation, it is correctness. With mergeMap, a slow request for "ab" can land after a fast one for "abc" and overwrite it — the user sees results for a query they already moved past. Because unsubscribing from an HttpClient observable aborts the in-flight request, switchMap also cancels the wasted work.

exhaustMap on a submit handler is the equivalent fix for double-clicks: while a submission is in flight, further clicks are ignored rather than queued.

filter, distinctUntilChanged, debounceTime, throttleTime, take, takeUntil, startWith, withLatestFrom.

distinctUntilChanged after debounceTime matters more than it looks: without it, typing “abc”, deleting to “ab”, and retyping “abc” fires two identical requests.

  • combineLatest — emits when any source emits, with the latest of each. Emits nothing until every source has emitted at least once, which is the most common “why is my stream silent” cause. startWith fixes it.
  • forkJoin — waits for all sources to complete, then emits once. Right for parallel HTTP calls, wrong for anything that does not complete.
  • merge — interleaves.
  • zip — pairs by index. Rarely what you want; a slow source stalls the pairing indefinitely.

catchError, retry, throwError, finalize.

The rule that catches everyone: an error terminates the observable. After error, that stream is dead — no further emissions, ever. A valueChanges stream that errors once stops working for the rest of the page’s life, silently.

So catchError placement is a real decision:

// Inside switchMap: the outer stream survives a failed request.
readonly results$ = this.query$.pipe(
switchMap((q) =>
this.search(q).pipe(catchError(() => of([]))),
),
);
// Outside: one failure kills the search box permanently.
readonly broken$ = this.query$.pipe(
switchMap((q) => this.search(q)),
catchError(() => of([])),
);

Handle errors inside the inner observable whenever the outer stream should keep working.

const RETRYABLE = new Set([0, 408, 429, 502, 503, 504]);
source$.pipe(
retry({
count: 3,
delay: (error: HttpErrorResponse, attempt) =>
RETRYABLE.has(error.status)
? timer(Math.min(1000 * 2 ** (attempt - 1), 8000))
: throwError(() => error),
}),
);

Bare retry(3) retries a 404 three times and hammers a failing server. Retry only idempotent operations, only retryable statuses, and with exponential backoff and a cap.

Every manual subscribe is a resource you own. In order of preference:

1. Do not subscribe. toSignal or the AsyncPipe subscribe and unsubscribe for you, and the AsyncPipe also calls markForCheck().

readonly user = toSignal(this.userService.currentUser$, { initialValue: null });

2. takeUntilDestroyed() when you genuinely need a side effect:

constructor() {
this.dispatcher.notifications
.pipe(takeUntilDestroyed())
.subscribe((message) => this.popup.show(message));
}

It uses DestroyRef to know when the component is destroyed, and needs no separate Subject — the pattern it replaces. Called outside an injection context, it needs an explicit DestroyRef:

private readonly destroyRef = inject(DestroyRef);
start(): void {
this.source$.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(/* ... */);
}

3. A manual Subscription only where lifetimes genuinely do not match the component.

HttpClient observables complete after their response, so an un-torn-down HTTP subscription usually will not leak — but the callback can still run against a destroyed component and fail there, so tear it down anyway.

Observables are cold by default: each subscriber gets its own execution. Two subscribers to http.get(url) produce two requests.

readonly config$ = this.http.get<Config>('/api/config').pipe(
shareReplay({ bufferSize: 1, refCount: true }),
);

shareReplay shares one execution and replays the last value to late subscribers. Always pass refCount: true unless you specifically want the subscription to outlive all subscribers — the default keeps the source subscribed forever, which for a WebSocket or an interval is a leak.

For request-scoped data, httpResource is usually the better answer than hand-rolled caching: it gives you status signals and automatic cancellation without any of this.

Type Behaviour
Subject No initial value; late subscribers miss earlier emissions
BehaviorSubject Requires an initial value; replays the latest
ReplaySubject(n) Replays the last n
AsyncSubject Emits only the final value, on completion

BehaviorSubject for state is now a signal. That is where most BehaviorSubject usage lived, and moving it removes the .value reads, the asObservable() boilerplate and the initialValue juggling.

Subject remains right for events: a notification bus, a “user clicked retry” signal, a dialog result. Things where every occurrence matters and there is no meaningful “current value.”

Expose asObservable() from services, always. A public Subject lets any consumer call next() on your stream.

From @angular/core/rxjs-interop:

toSignal(source$, options) — subscribes immediately (so side effects fire), unsubscribes on destroy, needs an injection context or an explicit injector. Handle the initial value with initialValue, accept undefined, or use requireSync: true for a source guaranteed to emit synchronously. If the source errors, the error is thrown when the signal is read. If it completes, the signal keeps the last value. Do not call it repeatedly for the same observable — each call is a new subscription.

toObservable(signal) — tracks the signal with an effect writing into a ReplaySubject. The first value may be synchronous on subscription; everything after is asynchronous. Coalesces rapid writes, as described above.

rxResource({ params, stream }) — a resource whose loader is an observable factory. The bridge for services that already expose observables, with the resource’s status signals and automatic cancellation.

takeUntilDestroyed(destroyRef?) — covered above.

outputFromObservable(source$) — makes a component output that emits when the observable does. Only callable in a property initialiser (the compiler treats it specially). Angular forwards subscriptions to the source and stops on destroy. Prefer plain output() when you can emit imperatively.

outputToObservable(ref) — an observable from a component output. OutputRef.subscribe is often enough on its own.

pendingUntilEvent() — keeps the application unstable until the source emits, completes, errors or is unsubscribed. Needed for SSR under zoneless. See SSR and Hydration.

Two approaches, and the simpler one covers most cases.

firstValueFrom / lastValueFrom with async tests:

it('filters by query', async () => {
const results = await firstValueFrom(service.search('acme'));
expect(results).toHaveLength(2);
});

Marble testing with TestScheduler for anything genuinely time-dependent:

it('debounces the query', () => {
new TestScheduler((actual, expected) => expect(actual).toEqual(expected))
.run(({ cold, expectObservable }) => {
const source = cold('a-b-c------|');
expectObservable(source.pipe(debounceTime(3))).toBe('---------c-|');
});
});

Marble tests are precise and expensive to read. Reserve them for operator chains where timing is the logic; use firstValueFrom for everything else.

Note that this is another argument for moving state to signals: expect(state.total()).toBe(25) needs no scheduler, no fixture, and no marble diagram.

Anti-pattern Why it hurts
subscribe inside subscribe Nested, uncancellable, error handling lost — use a flattening operator
mergeMap for search Out-of-order responses overwrite newer results
Bare retry(3) Retries unretryable errors; hammers a failing server
catchError outside switchMap One failure kills the outer stream permanently
Manual subscribe with no teardown Leak; callbacks against a destroyed component
Public Subject on a service Anyone can push into your stream
shareReplay() without refCount Source stays subscribed forever
.value on a BehaviorSubject Imperative read of reactive state — use a signal
combineLatest with a source that never emits Silent stream — add startWith
forkJoin on a non-completing source Never emits
BehaviorSubject for component state A signal is simpler in every dimension
toSignal called per render A new subscription each time
An operator chain nobody can read Extract named intermediate observables

“When would you still choose RxJS over signals?” When time, cancellation, or event coordination is involved. Debouncing, throttling, retry with backoff, cancelling a superseded request, combining several async sources, or consuming a long-lived external stream — none of those have a signal answer. Signals also coalesce: three writes in a tick produce one notification, so anything that must observe every occurrence needs a Subject. State, derived values, and template data belong in signals; the boundary between the two is toSignal.

“switchMap, mergeMap, concatMap, exhaustMap — pick one for each of: typeahead search, a submit button, uploading a queue of files.” Typeahead is switchMap: superseded requests should be cancelled, and cancelling an HttpClient subscription aborts the request, which also removes the out-of-order-response bug. A submit button is exhaustMap: while one submission is in flight, further clicks should be ignored, not queued — that is exactly the double-submit fix. A queue of uploads is concatMap if order matters or the server cannot handle concurrency, mergeMap if they are independent and you want them parallel.

“A valueChanges subscription stopped working halfway through a session. Why?” It errored. An error terminates an observable permanently — no further emissions, ever — and if nothing handled it, the failure is silent. The fix is catchError in the right place: inside the inner observable of a switchMap, so the outer stream survives. A catchError after the switchMap catches the error but the outer stream is already dead by then.

“Explain cold versus hot, and where it bites in Angular.” HttpClient observables are cold: nothing happens until subscription, and each subscription is an independent execution. So user$ | async used twice in a template makes two requests. shareReplay({ bufferSize: 1, refCount: true }) shares one execution and replays to late subscribers — and refCount: true matters, because without it the source stays subscribed after every subscriber has gone, which for an interval or a socket is a leak.

“How do you manage subscriptions in a modern Angular component?” Mostly by not having any. toSignal or the AsyncPipe subscribe and unsubscribe for you, and the AsyncPipe also handles change-detection notification. Where a genuine side effect needs a subscription, takeUntilDestroyed() in the constructor — it uses DestroyRef and needs no companion Subject. Outside an injection context it needs an explicit DestroyRef passed in. A manual Subscription array is a last resort for lifetimes that genuinely do not match the component’s.

“You inherit a service with fifteen BehaviorSubjects. What do you do?” Read what each one is. The ones holding current state become signals, and their map-derived streams become computed — that removes the .value reads, the asObservable() wrappers and most of the subscription management, and it makes the service testable without a scheduler. The ones representing events, where every occurrence matters, stay Subjects. The ones doing time-based work stay observables and get a toSignal at the boundary. I would do it feature by feature rather than all at once, because the interop is good enough that the two can coexist indefinitely.