RxJS and Observables

RxJS and Observables in Angular: Picture a municipal water-treatment plant. Raw water arrives continuously from the reservoir and flows through a fixed…

The Analogy: A Municipal Water-Treatment Pipeline

Picture a municipal water-treatment plant. Raw water arrives continuously from the reservoir and flows through a fixed sequence of inline stages: a screen removes debris, a dosing station adds treatment chemicals, a filtration bed traps particulates, and a final check lets only water meeting spec continue to the mains. The water is transformed as it travels, stage by stage, and the sequence is arranged once and then simply runs whenever water flows. An Observable is that pipeline: a stream of values arriving over time, threaded through an ordered chain of operators that each transform or screen what passes.

The crucial detail is that nothing flows until a tap is opened. The plant's stages can be fully plumbed and configured, but no water actually moves through them until a household downstream opens a faucet and creates demand. In RxJS this is subscription: an Observable is typically cold, meaning the pipeline is inert until subscribe is called, and each subscriber opens its own tap that runs the source through the operators independently. Define a stream and never subscribe, and not a drop moves.

Each operator is one station on the line. map is a dosing station that transforms every unit that passes; filter is a filtration bed that lets only conforming values continue; catchError is an emergency bypass valve that diverts to a safe fallback when a batch is contaminated; scan is a running reservoir that accumulates a total as water flows. And switchMap is the operator that switches the intake to a fresher upstream source, abandoning whatever batch was already mid-pipe so only the newest source reaches the mains.

The failure mode is the tap nobody closed. When a household moves out but leaves a faucet running, the plant keeps treating and pumping water that no one consumes, burning capacity indefinitely - this is a subscription never torn down, the classic RxJS memory leak. A subtler failure is choosing a "merge every source" flatten when you needed "switch to the latest": batches from an abandoned upstream source keep arriving, out of order, and stale water reaches the tap after fresh water already did.


Syntax or Core Structure

An Observable represents a stream of values delivered over time. You rarely create one by hand in Angular - HttpClient, router events, and form value changes all hand you one - but you always shape it the same way: chain operators inside .pipe(...), then consume the result in .subscribe(...). Each operator returns a new Observable, leaving the source untouched.

import { map, filter } from 'rxjs/operators';

this.userService.getUsers().pipe(
  filter(users => users.length > 0),
  map(users => users.filter(u => u.active))
).subscribe(active => this.users = active);

Because operators are just functions from a stream to a stream, a synchronous array captures their essence exactly. Modeling a stream as an array and each operator as a pure array function makes the data flow visible without any timing:

const map = fn => arr => arr.map(fn);
const filter = fn => arr => arr.filter(fn);
const pipe = (...ops) => arr => ops.reduce((acc, op) => op(acc), arr);

const source = [1, 2, 3, 4, 5];        // the stream's emissions
const result = pipe(
  filter(n => n % 2 === 1),            // keep odd values
  map(n => n * 10)                     // multiply each by 10
)(source);

console.log('emitted: ' + result.join(', '));

Output:

emitted: 10, 30, 50

The source "emits" 1 through 5; filter passes only the odd values, and map scales each. Read top to bottom, the pipe is the treatment line and the array is the water flowing through it.


Technical Depth: Cold Streams, Accumulation, and Flattening

Three ideas separate people who use RxJS from people who fight it: when a stream actually runs, how to accumulate across emissions, and how to flatten a stream of streams.

Cold streams and subscription

Most Observables are cold: the producer runs fresh for each subscriber, and not at all until someone subscribes. Opening two taps runs the source twice, independently. This model counts how many times the producer executes:

let taps = 0;
function coldSource() {   // the producer, re-run per subscription
  taps++;
  return [1, 2, 3];
}

console.log('before subscribe, taps: ' + taps);
const a = coldSource();   // first subscribe
const b = coldSource();   // second subscribe
console.log('after 2 subscribes, taps: ' + taps);
console.log('values: ' + a.join(','));

Output:

before subscribe, taps: 0
after 2 subscribes, taps: 2
values: 1,2,3

Accumulating with scan

scan threads an accumulator through every emission and emits the running result each time - a reservoir level that rises as water arrives. Unlike reduce, which emits once at the end, scan emits after each value, which is what you want for live totals.

function scan(fn, seed) {
  return arr => {
    let acc = seed;
    return arr.map(v => (acc = fn(acc, v)));
  };
}

const running = scan((acc, n) => acc + n, 0)([10, 20, 30]);
console.log('running: ' + running.join(', '));

Output:

running: 10, 30, 60

The common transforming operators divide neatly by what they do to the stream:

OperatorEffect on the streamWater-plant stage
mapTransforms each valueA dosing station
filterDrops non-matching valuesA filtration bed
scanEmits a running accumulationA rising reservoir level
catchErrorSubstitutes a fallback on errorAn emergency bypass valve

switchMap versus mergeMap

Both operators handle a stream whose values each map to another stream - a search term to an HTTP request. They differ in what happens to an in-flight inner stream when a new outer value arrives. mergeMap keeps them all; switchMap cancels the previous and keeps only the latest. Typing "a" then "b" should show only "b" results:

const inner = term => [term + '-p1', term + '-p2'];
const outer = ['a', 'b'];

// mergeMap: every inner stream survives, including the stale 'a'
const merged = outer.flatMap(inner);

// switchMap: only the latest outer's inner stream survives
const switched = inner(outer[outer.length - 1]);

console.log('mergeMap: ' + merged.join(', '));
console.log('switchMap: ' + switched.join(', '));

Output:

mergeMap: a-p1, a-p2, b-p1, b-p2
switchMap: b-p1, b-p2

For autocomplete, mergeMap lets the abandoned "a" results race in after "b", while switchMap guarantees the view reflects only the newest query.


Real World Example: A Typeahead Search Box

A search box that queries an API on every keystroke is the canonical RxJS use case, because it needs debouncing, de-duplication, and cancellation - exactly the operators above. The component below wires the input's valueChanges stream through debounceTime (wait for a pause), distinctUntilChanged (ignore no-op edits), and switchMap (cancel the previous request when a newer term arrives), then subscribes to push results into a field the template renders.

@Component({
  selector: 'app-typeahead',
  template: '<input [formControl]="box"><p>{{ results.join(", ") }}</p>'
})
export class TypeaheadComponent implements OnInit, OnDestroy {
  box = new FormControl('');
  results: string[] = [];
  private destroy$ = new Subject<void>();

  constructor(private api: SearchApi) {}

  ngOnInit() {
    this.box.valueChanges.pipe(
      debounceTime(200),
      distinctUntilChanged(),
      switchMap(term => this.api.search(term)),
      takeUntil(this.destroy$)
    ).subscribe(hits => this.results = hits);
  }

  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }
}

To verify the pipeline's logic deterministically, model the keystrokes as an array, apply distinctUntilChanged as a fold that drops consecutive duplicates, and take the latest term's search results (what switchMap guarantees survives):

const keystrokes = ['', 'a', 'a', 'an', 'ang'];
const search = term => [term.toUpperCase() + '#1', term.toUpperCase() + '#2'];

// distinctUntilChanged + drop the empty seed
const terms = keystrokes.filter((t, i) => t !== '' && t !== keystrokes[i - 1]);

// switchMap keeps only the newest term's results
const latest = terms[terms.length - 1];
const rendered = search(latest);

console.log('queries run: ' + terms.join(', '));
console.log('rendered: ' + rendered.join(', '));

Output:

queries run: a, an, ang
rendered: ANG#1, ANG#2

The debounceTime step keeps the app from firing a request on every intermediate character, and distinctUntilChanged collapses the repeated "a" so only three real queries leave the browser. switchMap is the load-bearing choice: if a slow response for "an" were still in flight when "ang" resolves, it is cancelled, so the box can never flash stale results for a term the user already replaced.

The template binds results directly, and each subscription writes into that field, which reads cleanly. The design also complements the reactive form: box.valueChanges is itself an Observable, so the whole feature is one declarative chain rather than manual event listeners.

There is, however, a genuine flaw worth naming precisely - and it is the failure mode from the analogy. This component gets it right with takeUntil(this.destroy$) plus ngOnDestroy, but the moment a developer copies this pattern and omits that teardown, the manual .subscribe(...) in ngOnInit never stops. Every time Angular destroys and recreates the component (a route change, an *ngIf toggle) a new subscription is added and the old one keeps its valueChanges handler alive - the tap left running forever, leaking memory and firing searches for a component no one is looking at.

The fix is to never hand-subscribe to a long-lived stream without a teardown: either pipe through takeUntil(destroy$) as shown, or - better still - drop the manual subscription entirely and render the stream with the AsyncPipe (results$ | async), which subscribes and unsubscribes in lockstep with the view.


Common Mistakes

  1. Forgetting to unsubscribe. A manual .subscribe() on a long-lived stream keeps running after the component is destroyed. Use takeUntil(destroy$), the take/first operators for one-shot streams, or the AsyncPipe, which unsubscribes automatically.
  1. Nesting subscribes. Calling .subscribe() inside another .subscribe() recreates callback-hell and leaks inner subscriptions. Flatten with switchMap, mergeMap, or concatMap so the whole flow is one chain.
  1. Using mergeMap where switchMap belongs. For typeahead and "latest wins" scenarios, mergeMap lets stale responses arrive out of order and overwrite fresh ones. Reach for switchMap whenever a new value should cancel the previous request.
  1. Expecting a cold Observable to run without subscribing. Nothing in a cold stream executes until .subscribe() (or an async pipe) opens the tap. A pipeline defined but never subscribed does absolutely nothing.
  1. Subscribing just to reassign a field. Writing stream.subscribe(v => this.value = v) when the template could bind stream$ | async adds a manual subscription you now have to tear down. Prefer the pipe.
  1. Mutating emitted values. Operators assume values flow through untouched. Mutating an emitted object inside map or tap can corrupt other subscribers of the same shared stream; return new objects instead.
  1. Putting side effects in map. map is for transformation and must be pure. Logging, navigation, or state writes belong in tap, which exists precisely for side effects.
  1. Ignoring the error channel. An unhandled error terminates the stream permanently - no further values, ever. Handle it with catchError (returning a fallback stream) so one failure does not kill the pipeline.
  1. Creating the pipeline inside the template or on every change detection. Building a new Observable each tick means each cycle subscribes afresh. Construct streams once (in a field initializer or ngOnInit) and reuse the reference.

Best Practices

  • Prefer the AsyncPipe over manual subscriptions. It subscribes when the view appears and unsubscribes when it leaves, eliminating the most common leak entirely.
  • When you must subscribe manually, always pair it with a teardown - a destroy$ Subject plus takeUntil, or one of the take/first/takeWhile limiting operators.
  • Keep map pure and push all side effects into tap. This keeps the data path predictable and makes streams easy to test by inspection.
  • Choose the flattening operator deliberately: switchMap for "latest wins", concatMap to preserve order, mergeMap for true concurrency, exhaustMap to ignore new values while one is in flight.
  • Debounce and de-duplicate user input with debounceTime and distinctUntilChanged before triggering network work, so you send the fewest requests possible.
  • Always give streams an error strategy. Wrap fallible inner streams in catchError so a single failure returns a safe value instead of tearing down the whole pipeline.
  • Suffix Observable variables with $ (users$, results$). The convention makes it obvious at a glance which values are streams and which are plain data.
  • Model application state as streams end to end where it fits, letting the template be the only subscriber. Fewer imperative .subscribe() calls means fewer places for state and teardown bugs to hide.

Practice Exercises

  1. Build a debounced search. Create a component with a FormControl and pipe its valueChanges through debounceTime(300), distinctUntilChanged, and switchMap into a mock search service that returns an Observable of string arrays. Render the results with the AsyncPipe and confirm no manual subscription is needed.
  1. Prove the leak, then fix it. Write a component that subscribes to an interval-style stream in ngOnInit with no teardown, log inside the subscribe callback, and toggle the component with *ngIf to watch duplicate logs pile up. Then add a destroy$ Subject with takeUntil and ngOnDestroy, and verify the logs stop.
  1. Compare the flattening operators. Given a stream of search terms, implement the same inner request with switchMap, then mergeMap, then concatMap, and describe in comments how the visible results differ for rapid input. Predict the output ordering before running.
  1. Add resilient error handling. Take a stream whose inner request can fail, wrap it in catchError that returns a fallback Observable (for example of([])), and confirm the outer stream keeps emitting for subsequent inputs instead of terminating on the first error.