Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 74 ยท HTTP and RxJS

RxJS Operators You Need

Learn the RxJS operators Angular developers use daily: map, filter, tap, switchMap, mergeMap, concatMap, debounceTime, combineLatest, catchError, with runnable stand-ins.

An observable on its own just emits values. Operators are what make streams useful: functions that take one observable and return a new one, so you can transform, filter, combine and tame values with small, reusable steps. You chain them with pipe(), and the result reads like a recipe from top to bottom.

RxJS has well over a hundred operators, but daily Angular work uses about a dozen. This lesson teaches those, with the one idea that causes most confusion (the flattening operators switchMap, mergeMap and concatMap) explained slowly. You will also meet the classic typeahead pipeline and the operators that keep subscriptions from leaking.

The typescript blocks show real RxJS and Angular code and are read-only, because the site can't run Angular or install npm packages. The runnable examples are stand-ins: a compact Observable with a typed pipe() and hand-written versions of the operators, so that you can run the same ideas in this page. They are simplified (for example, they skip some edge cases real RxJS handles) and are not RxJS itself.

pipe() and operators

An operator is a function from observable to observable. pipe applies them in order, each receiving the output of the previous one. Nothing runs until someone subscribes, and each subscriber gets its own run (for a cold source):

TypeScript
import { of, map, filter, tap } from 'rxjs';

of(1, 2, 3, 4, 5, 6)
  .pipe(
    filter((n) => n % 2 === 0),   // keep 2, 4, 6
    map((n) => n * 10),           // 20, 40, 60
    tap((n) => console.log('about to emit', n)),   // side effect, value passes through
  )
  .subscribe((n) => console.log(n));

Since RxJS 7.2 you can import operators straight from 'rxjs', as above (older code imports them from 'rxjs/operators'). The ones you will use constantly:

Operator What it does
map(fn) transforms each value
filter(fn) lets only matching values through
tap(fn) runs a side effect (logging, debugging) without changing values
distinctUntilChanged() drops a value equal to the previous one
debounceTime(ms) emits a value only after ms of silence
switchMap, mergeMap, concatMap, exhaustMap for each value, start an inner observable (such as an HTTP call) and flatten the results
combineLatest([a, b]) emits the latest value of each source whenever any of them emits (once all have emitted at least once)
catchError(fn) handles an error by switching to a fallback observable
takeUntilDestroyed() completes the stream when the component or service is destroyed

Keep tap for logging and debugging. Putting real state changes inside it hides the data flow; do those in subscribe, or better still end the pipeline in a signal (Signals and RxJS interop).

Transforming and combining: a first runnable set

The stand-in below contains the Observable class (compact, same rules as in the previous lesson), a pipe method with typed overloads, a small Subject, and the operators map, filter, tap, distinctUntilChanged, catchError plus combineLatest. Everything here is synchronous, so the output is exact.

TypeScript Stand-in: pipe, map, filter, tap, catchError, combineLatest

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Look at the last line: nothing is emitted until both sources have produced a value, and after that every new value from either side produces a pair using the other side's latest. This is how you combine, say, a page number and a filter into one query. Also notice that in step 3 the map ran on 1 and 2 first, and then the error was replaced by -1: catchError doesn't undo what already came through, it only decides what happens instead of the error.

The flattening operators

Often each value should start more asynchronous work: a user types, so you search; a route param changes, so you load a record. The work is itself an observable, and if you used map, you'd get an observable of observables. Flattening operators subscribe to each inner observable for you and merge their results into one stream. They differ in one decision: what to do when a new outer value arrives while the previous inner work is still running.

Operator New value arrives while busy Typical use
switchMap cancel the previous inner, start the new one search as you type, loading data for the current route
mergeMap start it in parallel; results come in finishing order independent tasks such as uploading many files
concatMap queue it; run one at a time, in order saving changes where order matters
exhaustMap ignore the new value until the current one ends a submit or login button against double clicks

For HTTP GETs that fetch the "current" thing, switchMap is nearly always right, because a stale answer must never overwrite a fresh one, and cancelling the old request saves bandwidth. For writes, think carefully: cancelling a POST in the browser doesn't un-send it, so concatMap or exhaustMap are usually the safer choices.

The second stand-in implements switchMap, mergeMap, concatMap, debounceTime, distinctUntilChanged and takeUntil, then runs the three flatteners on the same input so you can compare them. Three outer values (a, b, c) arrive 20 ms apart, and each starts a fake request taking 150, 90 and 30 ms.

TypeScript Stand-in: switchMap vs mergeMap vs concatMap, and a typeahead

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The three flatteners got identical input and gave three different answers. switchMap produced a single response: a and b were cancelled (they appear in the cancelled list because their teardown ran before they finished), so only the latest request survived. mergeMap kept all three and delivered them in the order they finished (c, then b, then a), which is not the order they started. concatMap ran them one after another, so results keep the input order but arrive last. In the typeahead, three quick keystrokes became one search (abc), the repeated abc was dropped by distinctUntilChanged, abcd caused a second search, and after the "destroy" signal the stream completed and the subject lost its listener, so late went nowhere.

The typeahead in real Angular

Here is the same pipeline as it appears in a component, using real RxJS and Angular APIs (read-only):

TypeScript
import { Component, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { catchError, debounceTime, distinctUntilChanged, map, of, switchMap } from 'rxjs';

@Component({
  selector: 'app-search',
  imports: [ReactiveFormsModule],
  template: `
    <input [formControl]="term" placeholder="Search" />
    @for (hit of results(); track hit.id) {
      <p>{{ hit.title }}</p>
    }
  `,
})
export class SearchComponent {
  private readonly api = inject(SearchApi);
  protected readonly term = new FormControl('', { nonNullable: true });

  protected readonly results = toSignal(
    this.term.valueChanges.pipe(
      debounceTime(300),
      map((text) => text.trim()),
      distinctUntilChanged(),
      switchMap((text) =>
        text.length < 2
          ? of([])
          : this.api.search(text).pipe(catchError(() => of([]))),   // inside, so the outer stream survives
      ),
    ),
    { initialValue: [] },
  );
}

Notice where catchError sits: inside the switchMap. An error that reaches the outer stream ends it for good, and a typeahead that dies after the first failed request is a classic bug. Handling the error on the inner request turns a failure into "no results" and keeps listening. toSignal subscribes, exposes the latest value as a signal, and unsubscribes when the component is destroyed (read more in Signals and RxJS interop).

flowchart LR
  K["Keystrokes<br/>valueChanges"] --> D["debounceTime(300)"]
  D --> M["map(trim)"]
  M --> U["distinctUntilChanged()"]
  U --> S["switchMap(search)<br/>cancels stale requests"]
  S --> R["results signal"]

Each step makes the stream calmer, so the server sees fewer, fresher requests.

Combining and cleaning up

combineLatest is the right tool when several streams jointly determine one result, such as a page number, a sort order and a filter text that together form a query:

TypeScript
const query$ = combineLatest([this.page$, this.sort$, this.filter$]).pipe(
  debounceTime(0),                       // merge changes that happen together
  switchMap(([page, sort, filter]) => this.api.list({ page, sort, filter })),
);

(Real combineLatest takes an array or an object of sources, and a source that never emits keeps the whole result silent.) Related tools are forkJoin, which waits for several observables to complete and emits once, good for parallel one-shot HTTP calls, and withLatestFrom, which samples another stream only when the main one emits.

For cleanup, remember takeUntilDestroyed() from @angular/core/rxjs-interop. Put it last in the pipe, so everything upstream is torn down:

TypeScript
constructor() {
  this.router.events
    .pipe(filter((event) => event instanceof NavigationEnd), takeUntilDestroyed())
    .subscribe((event) => this.analytics.pageView(event.urlAfterRedirects));
}

Called without arguments, it works inside an injection context such as a constructor or field initializer; elsewhere pass a DestroyRef.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A user types quickly in a search box and each term triggers an HTTP search. Which operator ensures that an old, slow response can never replace a newer one?

    switchMap cancels the previous inner observable when a new value arrives, so only the latest search can deliver results.
  2. 2. You must upload ten files in parallel, and the order of the results does not matter. Which operator fits best?

    mergeMap starts every inner observable immediately and emits results as they finish. switchMap would cancel earlier uploads.
  3. 3. What does debounceTime(300) do?

    Each new value restarts the timer, so only the last value of a burst is emitted once the stream falls quiet.
  4. 4. Where should catchError go in a switchMap typeahead so that one failed request does not end the whole stream?

    An error that reaches the outer stream terminates it. Handling it on the inner observable turns it into a fallback value and the outer stream keeps listening.
  5. 5. When does combineLatest([a$, b$]) first emit?

    combineLatest needs a value from every source before it can produce its first array; after that it emits whenever any source emits.

Summary

  • Operators are functions from observable to observable; pipe() chains them, and nothing runs until you subscribe.
  • Everyday set: map, filter, tap (for side effects like logging), distinctUntilChanged, debounceTime, combineLatest, catchError, takeUntilDestroyed.
  • Flattening operators differ in what happens when a new value arrives while inner work is running: switchMap cancels, mergeMap runs in parallel, concatMap queues, exhaustMap ignores.
  • Use switchMap for "latest wins" reads like search; use concatMap or exhaustMap for writes.
  • Put catchError on the inner request, and takeUntilDestroyed() last in the pipe.
  • The RxJS and Angular snippets are read-only; the compact operators on this page are stand-ins.

Next: HttpClient: Requests and Responses