Back to all posts
·7 min read

Managing RxJS streams in Angular: the right operator, cancellation and subscription leaks

A good share of the hard bugs in Angular applications do not come from RxJS itself, but from nobody having thought about a stream's lifetime and its concurrency behavior. An old result overwriting a newer one when you type quickly into a search box, two records created because the save button was pressed twice, a timer still running after the page was left: these are all different faces of the same problem.

In this post I describe the three questions I ask myself when writing a stream: when will this subscription end, what happens to the work in progress when a new value arrives, and will the stream stay alive if an error occurs? Once those three questions get deliberate answers, RxJS code stops being surprising.

A subscription is a resource and needs an owner

Calling subscribe opens a resource: a listener, a timer or an open connection. If the source never completes and the subscription is never closed, it keeps running after the component has been destroyed. The result is not just a memory leak; the callback of a component that is no longer on screen runs, updates state and sometimes starts new requests.

It helps to separate the streams that carry risk. HttpClient calls emit a single value and complete; the leak risk is low, but if the response arrives after the component is destroyed, the callback still runs. interval, fromEvent, a form control's valueChanges, a Subject in a service or router events, on the other hand, do not complete on their own. Any code that subscribes to these has to state its end condition explicitly.

My rule is this: wherever I write subscribe by hand, how the subscription ends should be visible in the same group of lines.

Declaring the end: takeUntilDestroyed, the async pipe and toSignal

The simplest way to provide an end condition is the takeUntilDestroyed operator. It completes the stream when the component, directive or service is destroyed:

import { takeUntilDestroyed } from '@angular/core/rxjs-interop';

export class OrderListComponent {
  private readonly orders = inject(OrderService);

  constructor() {
    this.orders.changes$
      .pipe(takeUntilDestroyed())
      .subscribe(change => this.apply(change));
  }
}

The parameterless form needs an injection context, so it has to be called in the constructor or a field initializer. If you use it somewhere else, such as ngOnInit, inject DestroyRef and pass it as takeUntilDestroyed(this.destroyRef). It also matters that the operator sits near the end of the chain; a switchMap placed after it can open a new inner stream that falls outside its scope.

Often the better solution is not to subscribe by hand at all. The async pipe in the template opens and closes the subscription together with the view. toSignal brings the same idea to the signal world: it subscribes to the stream, exposes the latest value as a signal and closes the subscription when its context is destroyed.

readonly orders = toSignal(this.orderService.list(), { initialValue: [] });

Writing subscribe by hand makes sense when you really need to trigger a side effect, not when you just want to get data onto the screen.

Four flattening operators, four different concurrency decisions

If you start new asynchronous work when a value arrives, you choose between switchMap, mergeMap, concatMap and exhaustMap. These are not interchangeable tools; each one answers the question "what happens if a new value arrives while the previous work is still running" differently.

  • switchMap: cancels the previous work; only the latest matters. Suitable for reads such as search, filtering or loading data based on a route parameter.
  • concatMap: queues the work and runs it one at a time in arrival order. Suitable for writes where order matters.
  • mergeMap: runs everything in parallel with no ordering guarantee. Suitable for independent work; a limit can be passed as the second parameter to cap concurrency.
  • exhaustMap: ignores new values until the running work finishes. Suitable where a double click does damage, such as submitting a form, signing in or a refresh button.

The mistake I see most often is using switchMap everywhere out of habit. If you use switchMap for a save request, the second click cancels the subscription of the first; but the request may already have reached the server. You end up with two records on the server and only the second response on the client. For writes, my default choice is concatMap or exhaustMap.

Example: a cancellable search box

The classic example where these decisions come together is an input that searches as you type:

readonly query = new FormControl('', { nonNullable: true });

readonly results$ = this.query.valueChanges.pipe(
  map(text => text.trim()),
  debounceTime(300),
  distinctUntilChanged(),
  switchMap(text =>
    text.length < 2 ? of([]) : this.search.find(text)
  )
);

debounceTime waits until the user stops typing and prevents a request on every keystroke. distinctUntilChanged does not repeat the request for the same text. switchMap does the important part: when a new query arrives, it unsubscribes from the previous inner stream. HttpClient cancels the in-flight request in that case, so a late response to an old query cannot overwrite the new result.

Trying to solve this race condition without switchMap, using nested subscribe calls, is both longer and more fragile. Wherever I see a nested subscribe, there is almost always a missing flattening operator.

An error ends the stream: putting catchError in the right place

In RxJS an error is a stream's final notification. A stream that has errored never emits again. If a single request fails in the search above and the error reaches the outer stream, the input will not trigger any search from then on; from the user's point of view the search box has silently broken.

The fix is to catch the error inside the inner stream, before it reaches the outer one:

switchMap(text =>
  this.search.find(text).pipe(
    map(items => ({ status: 'ok' as const, items })),
    catchError(() => of({ status: 'error' as const, items: [] }))
  )
)

There are two details here. The first is position: if catchError is placed on the outer chain, the error is caught but the stream still completes; when it is caught in the inner stream, only that request ends and the outer stream keeps listening. The second is content: swallowing the error by turning it into an empty list makes "no results" and "search failed" indistinguishable. Modeling the error as part of the state lets the UI show the right message.

Retries belong in the same place, the inner stream, and should only be used for operations that are safe to repeat.

Sharing: not sending the same request five times

The streams returned by HttpClient are cold; every subscription starts a new request. If you use the same stream with the async pipe in three places in a template, three requests go out. This usually goes unnoticed until someone looks at the network tab.

To share the result between subscribers, use shareReplay:

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

bufferSize: 1 hands the latest value to subscribers that arrive later. refCount: true closes the subscription to the source when the last subscriber leaves; without it, on a source that does not complete, the subscription stays open even when nobody is listening. You also need to think about the lifetime of the cache: a shared stream held at service level does not refresh itself when the data changes. Building the refresh on an explicit trigger, for example a Subject with switchMap, is more predictable.

What I ask when reviewing streams

When I look at an RxJS chain in code review, I work through a short list:

  • When does this subscription end, and can that be read from the code?
  • Was the flattening operator chosen deliberately; is the work a read or a write?
  • Is the error caught in the inner stream, or does it kill the whole stream?
  • Does the same cold stream have more than one subscriber?
  • Is there a nested subscribe, or state being copied by hand inside a subscribe?

The learning curve of RxJS is usually associated with the number of operators, but what daily work requires is narrower: deciding who owns the subscription, expressing the concurrency decision explicitly through the operator and handling the error where it will not kill the stream. Once these three are in place, the remaining operators are just details; and when used alongside Signals, the area left to RxJS, namely events spread over time and cancellation, ends up defined by a much clearer boundary.