TypeScript · Lesson 12

RxJS & Observables

RxJS the way Angular uses it, with the real library. Observables and subscriptions, operators and marble diagrams, Subjects, the four flattening operators, error handling, multicasting, leaks, signals interop and marble testing.

9 min read

In short

  • Observables are lazy, many-valued and cancellable
  • Operators chain in pipe; types flow through
  • switch cancels, concat queues, exhaust ignores, merge runs all
  • Errors end streams: catch inside the inner Observable
  • Share cold sources, and unsubscribe from ones that don't complete

Angular is built on RxJS. HttpClient, the router, reactive forms, @Output()s and interceptors all hand you Observables, and a lot of an Angular codebase is RxJS pipelines. This topic teaches the parts you'll use every day, and the mistakes that cause most RxJS bugs.

The lab runs the real RxJS 7. import { ... } from 'rxjs' works in the playground and in the exercises, with full IntelliSense, so every snippet below has a ▶ Try button. The exercises use the real operators and are graded with RxJS's own TestScheduler (marble tests in virtual time). Snippets that need Angular itself are shown without a Try button.

Observables in one page

An Observable is a function that can deliver many values over time, then complete or fail, and that you can cancel. Nothing happens until someone subscribes:

▶ Try
import { Observable } from 'rxjs';

const ticks$ = new Observable<number>((subscriber) => {
  console.log('producer starts');
  let n = 0;
  const id = setInterval(() => subscriber.next(n++), 20);
  return () => {
    clearInterval(id); // teardown: runs on unsubscribe, complete or error
    console.log('producer stopped');
  };
});

console.log('nothing has happened yet');
const subscription = ticks$.subscribe((n) => console.log('tick', n));
setTimeout(() => subscription.unsubscribe(), 70);
PromiseObservable
valuesexactly onezero, one or many
startsimmediately (eager)on subscribe (lazy), again for every subscriber
cancelnot built in (needs AbortSignal)unsubscribe() runs the teardown
composethen~100 operators in pipe(...)

The $ suffix (ticks$) is just a naming convention for "this is an Observable".

Operators, pipe and marble diagrams

Operators are functions from Observable to Observable, chained with pipe. Types flow through the chain:

▶ Try
import { filter, map, of, scan } from 'rxjs';

of(3, 8, 1, 12, 5)
  .pipe(
    filter((n) => n > 2),       // 3 8 12 5
    map((n) => n * 10),         // 30 80 120 50
    scan((sum, n) => sum + n, 0), // running total
  )
  .subscribe({ next: (total) => console.log(total), complete: () => console.log('complete') });

RxJS behaviour is described with marble diagrams. You'll see them in docs, in code reviews and in the exercises' tests:

marblemeaning
-one frame (1 ms of virtual time) passes
a, b, 1a value is emitted (and takes up one frame)
|complete
#error
(ab)a and b in the same frame (the group takes up as many frames as it has characters)
^ / !subscription starts / ends (in subscription marbles)
10mstime progression: 10 ms pass

So -a--b| means a at 1 ms, b at 4 ms, complete at 5 ms. With TestScheduler.run, time-based operators (debounceTime, delay, timer, interval) run in virtual time: a test of a 300 ms debounce takes no real time.

▶ Try
import { debounceTime } from 'rxjs';
import { TestScheduler } from 'rxjs/testing';

const scheduler = new TestScheduler((actual, expected) => {
  console.log(JSON.stringify(actual) === JSON.stringify(expected) ? 'marbles match' : 'marbles differ');
});

scheduler.run(({ cold, expectObservable }) => {
  const typing = cold('a 10ms b 30ms c|'); // a at 0, b at 11, c at 42, complete at 43
  expectObservable(typing.pipe(debounceTime(20))).toBe('31ms b 11ms (c|)');
});

Subjects: Observables you push into

A Subject is both an Observable and an observer: you call next(value) on it, and every current subscriber gets it. Subjects are hot: values are delivered whether or not anyone is listening.

▶ Try
import { BehaviorSubject, ReplaySubject, Subject } from 'rxjs';

const events = new Subject<string>();
const state = new BehaviorSubject('initial');
const history = new ReplaySubject<string>(2);

for (const s of [events, state, history]) s.next('first');
for (const s of [events, state, history]) s.next('second');

events.subscribe((v) => console.log('Subject       ', v));
state.subscribe((v) => console.log('BehaviorSubject', v));
history.subscribe((v) => console.log('ReplaySubject ', v));
  • Subject: late subscribers get nothing from before. Use it for events and signals ("save clicked").
  • BehaviorSubject: has a current value (.value), which a new subscriber gets immediately. Use it for state.
  • ReplaySubject(n): replays the last n values to new subscribers.
  • Expose them with asObservable(), so only the owner can call next (the store exercise).

The four flattening operators

When each value starts another Observable (typically an HTTP call), you need a flattening operator. Each one handles "a new value arrives while the previous inner Observable is still running" differently:

▶ Try
import { concatMap, exhaustMap, interval, lastValueFrom, map, mergeMap, OperatorFunction, switchMap, take, timer, toArray } from 'rxjs';

const clicks$ = interval(40).pipe(take(3)); // clicks at 40, 80 and 120 ms
const save = (n: number) => timer(100).pipe(map(() => `saved ${n}`)); // each save takes 100 ms

const strategies: Array<[string, OperatorFunction<number, string>]> = [
  ['switchMap', switchMap(save)],
  ['mergeMap', mergeMap(save)],
  ['concatMap', concatMap(save)],
  ['exhaustMap', exhaustMap(save)],
];

async function main() {
  for (const [name, strategy] of strategies) {
    const results = await lastValueFrom(clicks$.pipe(strategy, toArray()));
    console.log(name.padEnd(10), results.join(', '));
  }
}
main();
operatornew value while busyuse it for
switchMapcancels the running onereads where only the latest matters: search, route params, filters
concatMapqueues itwrites that must happen in order: autosave, a queue of updates
exhaustMapignores it"do once until done": submit, login, refresh buttons
mergeMapruns it in parallel (mergeMap(fn, n) caps it)independent work: uploads, per-item requests

Never nest subscribe calls. outer$.subscribe(x => http.get(x).subscribe(...)) is a mergeMap without cancellation, error handling or completion.

Errors end streams

An error is terminal: after it, the Observable emits nothing more. Where you catch it decides what survives:

▶ Try
import { catchError, concatMap, of, throwError } from 'rxjs';

const load = (id: number) => (id === 2 ? throwError(() => new Error(`item ${id} failed`)) : of(`item ${id}`));

// catchError on the outer stream: the whole stream is replaced and ends.
of(1, 2, 3)
  .pipe(concatMap(load), catchError(() => of('fallback')))
  .subscribe({ next: (v) => console.log('outer:', v), complete: () => console.log('outer: done') });

// catchError inside the inner Observable: only that item is replaced.
of(1, 2, 3)
  .pipe(concatMap((id) => load(id).pipe(catchError(() => of(`item ${id} unavailable`)))))
  .subscribe({ next: (v) => console.log('inner:', v), complete: () => console.log('inner: done') });

Related tools:

  • retry({ count, delay }) resubscribes after an error (the polling exercise).
  • finalize(fn) runs on complete, error or unsubscribe, for things like hiding a spinner.
  • throwError(() => err) creates an Observable that fails.
  • EMPTY completes immediately without a value.

Cold, hot and sharing

Cold Observables (HTTP calls, of, defer, timer) start a new execution per subscriber. Three async pipes on http.get(...) make three requests. Multicasting operators share one execution:

▶ Try
import { defer, of, shareReplay } from 'rxjs';

let requests = 0;
const user$ = defer(() => {
  requests++;
  return of({ name: 'Ann' });
});

user$.subscribe();
user$.subscribe();
console.log('cold, 2 subscribers:', requests, 'requests');

requests = 0;
const shared$ = user$.pipe(shareReplay({ bufferSize: 1, refCount: true }));
shared$.subscribe();
shared$.subscribe();
console.log('shared, 2 subscribers:', requests, 'request');

shareReplay({ bufferSize: 1, refCount: true }) is the safe default for "share and give late subscribers the latest value". Without refCount: true, a source that never ends stays subscribed after every component is gone. The shareLatest exercise builds it from scratch.

Subscriptions and leaks in Angular

Every subscribe needs a matching unsubscribe, or a reason it doesn't need one:

  • Prefer not subscribing yourself. The async pipe (@let user = user$ | async) and toSignal(user$) subscribe and unsubscribe with the component.
  • takeUntilDestroyed() (in an injection context, or pass a DestroyRef) ends a manual subscription when the component is destroyed.
  • Completing sources are safe. HttpClient calls emit once and complete. valueChanges, interval, router events, store selectors and WebSockets don't, and they're where leaks come from.
import { Component, inject } from '@angular/core';
import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
import { ActivatedRoute } from '@angular/router';
import { map, switchMap } from 'rxjs';

@Component({ /* ... */ })
export class OrderPage {
  private readonly route = inject(ActivatedRoute);
  private readonly api = inject(OrderApi);

  readonly order = toSignal(
    this.route.paramMap.pipe(
      map((params) => params.get('id')!),
      switchMap((id) => this.api.getOrder(id)),
    ),
  );

  constructor() {
    inject(NotificationsService).events$.pipe(takeUntilDestroyed()).subscribe((e) => this.toast(e));
  }
}

RxJS and signals

Modern Angular uses signals for state that templates read, and RxJS for events and async coordination: HTTP, debouncing, cancellation, websockets.

  • toSignal(obs$) gives you a signal of the latest value. Give it an initialValue, or use requireSync when the source emits synchronously (BehaviorSubject, startWith).
  • toObservable(signal) turns a signal's changes into an Observable, for example to debounceTime a search signal and switchMap it to HTTP.
  • resource() / httpResource() (signal-based async loading) handle the switchMap-style cancellation for simple loads.

Rule of thumb: if it's state ("what is the current value?"), use a signal. If it's events over time ("what happens when, in what order, and what gets cancelled?"), use RxJS.

Testing RxJS code

  • Marble tests (TestScheduler.run) for operators and pipelines. They're deterministic, fast and test timing exactly. Use cold(...) for things that start on subscribe (HTTP) and hot(...) for things that run anyway (clicks, a Subject).
  • Angular component tests: fakeAsync + tick(ms) moves virtual time for debounceTime & co. The HttpTestingController answers HTTP calls.
  • Test behaviour, not implementation: what is emitted when, and what is subscribed and unsubscribed when.

F# for comparison

Side note

.NET has IObservable<'T> built in, and F# events implement it. The Observable module has the basic operators. (Rx.NET, System.Reactive, adds the full RxJS-style set.)

▶ Try
let clicks = Event<int>()

clicks.Publish
|> Observable.filter (fun n -> n % 2 = 0)
|> Observable.map (fun n -> n * 10)
|> Observable.add (printfn "got %d")

for i in 1 .. 5 do clicks.Trigger i

The exercises

  1. A countdown with timer and take: your first stream over time, tested in virtual time.
  2. Cart totals with scan: state from events, with startWith and distinctUntilChanged.
  3. Pick the right flattening operator: switchMap, concatMap, exhaustMap and mergeMap on four real features.
  4. Typeahead search: debounce, cancel, keep working after errors, and a view-state union for the template.
  5. Poll a long-running job: defer, retry with backoff, repeat and a final state, for cloud long-running operations.
  6. A store service: BehaviorSubject, selectors, shareReplay and the combineLatest glitch.
  7. Write switchMap and exhaustMap yourself: custom operators with new Observable and teardown.
  8. Build shareLatest: multicasting with a ReplaySubject and reference counting.

Practise this lesson

In the app: a short video, 8 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.

Open in the app