Race conditions in RxJS and how switchMap fixes them

Here's a search box that looks fine in a demo and breaks on a slow network:

Here’s a search box that looks fine in a demo and breaks on a slow network:

ngOnInit() {
  this.query.valueChanges.subscribe((term) => {
    this.products.search(term).subscribe((results) => {
      this.results = results;
    });
  });
}

Type “lap”, then “laptop”. Two requests go out. If the one for “lap” happens to come back last, the list shows results for “lap” while the input says “laptop”. Nothing in this code says which response should win, so whichever arrives last does.

On top of that, the inner subscriptions never get cleaned up, and every key press fires a request.

The fix

@Component({
  selector: 'app-search',
  standalone: true,
  imports: [ReactiveFormsModule, NgFor, AsyncPipe],
  template: `
    <input [formControl]="query" placeholder="Search products" />
    <ul>
      <li *ngFor="let p of results$ | async">{{ p.name }}</li>
    </ul>
  `,
})
export class SearchComponent {
  query = new FormControl('', { nonNullable: true });
  private products = inject(ProductService);

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

Each operator does one job:

  • debounceTime(300) waits for a short pause in typing, so we don’t send a request per key press.
  • distinctUntilChanged() skips the request if the term didn’t actually change, for example after typing a letter and deleting it.
  • switchMap is the one that fixes the race. When a new term comes in, it unsubscribes from the previous request before starting the next one.

With HttpClient, unsubscribing really does cancel the HTTP request, and you can see it marked as cancelled in the network tab. Even when a request can’t be cancelled, its result is ignored. A stale response can’t reach the list anymore.

The catchError sits inside switchMap on purpose. If an error reaches the outer stream, the whole stream completes and the search box stops working until the page reloads. Catching it per request means one failed search doesn’t kill the next one.

The async pipe subscribes and unsubscribes for us, so there’s no cleanup code to forget.

The same bug on route params

This race isn’t limited to search boxes. A product page that loads data based on the URL has the same problem when the user clicks quickly between products:

product$ = this.route.paramMap.pipe(
  map((params) => params.get('id')!),
  switchMap((id) => this.products.getProduct(id)),
);

Angular reuses the component when only the param changes, so without switchMap you can end up showing product 12 on the URL for product 13.

Picking the right operator

switchMap isn’t always correct. All four of these turn a value into a request, and they differ in what happens when a new value arrives while a request is still running:

Operator When a new value arrives Good for
switchMap cancels the running request search, loading data for the current selection
concatMap waits, then runs it after the current one saves that must happen in order
mergeMap runs both in parallel independent work where order doesn’t matter
exhaustMap ignores the new value submit buttons, login

Using switchMap for saves is a real bug. If autosave fires twice quickly, the first save might be cancelled halfway. concatMap keeps them in order:

this.saves
  .pipe(
    concatMap((draft) => this.http.put(`/api/drafts/${draft.id}`, draft)),
    takeUntilDestroyed(),
  )
  .subscribe();

And exhaustMap is a neat way to stop double submits without disabling buttons by hand:

this.submits
  .pipe(
    exhaustMap(() => this.http.post('/api/orders', this.order)),
    takeUntilDestroyed(),
  )
  .subscribe(() => this.router.navigate(['/thanks']));

takeUntilDestroyed

Those last two examples use takeUntilDestroyed, which is new in Angular 16 (in developer preview for now). It completes the stream when the component is destroyed, so you don’t need the old destroy$ subject and ngOnDestroy boilerplate.

It needs an injection context, so call it in the constructor or in a field initializer. Anywhere else, like ngOnInit, pass a DestroyRef yourself:

private destroyRef = inject(DestroyRef);

ngOnInit() {
  this.products
    .search('x')
    .pipe(takeUntilDestroyed(this.destroyRef))
    .subscribe();
}

Still, if the value ends up in the template, the async pipe is the simpler choice. I only reach for a manual subscribe when the result is a side effect, like a save or a navigation.

A quick smell test

If you see a subscribe inside another subscribe, there’s almost certainly a race condition or a leak in it. Rewrite it as one stream with the right *Map operator, and decide on purpose what should happen when a new value arrives before the old one is done.