← Back to Angular, page 8

angular-0142 · Hard senior

How does an Observable work internally? Implement a tiny Observable and a map operator to show subscribe, teardown and operator chaining.

An Observable is a function that takes a subscriber and returns a teardown. subscribe calls that function with an observer, and an operator is a function that takes a source Observable and returns a new one that subscribes to the source inside its own subscribe function. Unsubscribing runs the teardown logic of the whole chain.

Full answer

RxJS looks magic, but the core fits in a few lines.

Observable: an object that wraps a function, often called subscribe or the producer. The function receives a subscriber (an object with next, error and complete) and may return a teardown function. Nothing happens until someone calls subscribe(observer). That explains why observables are lazy, and why every subscribe runs the producer again (cold).

Subscriber rules (the "contract"): after error or complete, no more values are delivered, and the teardown runs once. After unsubscribe, values are ignored and the teardown runs.

Operator: a function from Observable to Observable. map(fn) returns source => new Observable(subscriber => source.subscribe({ next: v => subscriber.next(fn(v)), error: e => subscriber.error(e), complete: () => subscriber.complete() })). The returned teardown is the inner subscription's unsubscribe, so cancelling the outer subscription cancels the source. pipe(...ops) just applies the operators in order: ops.reduce((src, op) => op(src), this).

What this teaches:

  • Lazy and cold: no producer runs until subscribe, and each subscriber gets its own run.
  • Chain of teardowns: unsubscribing at the end of a pipeline walks back to the source and clears timers and listeners. This is how switchMap cancels HTTP requests, and why forgetting to unsubscribe from an infinite source leaks.
  • Synchronous by default: of(1,2,3) calls next three times inside subscribe, before it returns.
  • Errors flow down the chain, and operators that do not catch them pass them along.

The real implementation adds a Subscriber class that enforces the contract, Subscription objects that hold several teardowns, operators written with operate helpers, and scheduler support. Understanding the small version makes operators like switchMap easy to reason about: they create inner observables, subscribe, and manage inner teardowns.

typescript
type Teardown = (() => void) | void;

interface Observer<T> {
  next(value: T): void;
  error(err: unknown): void;
  complete(): void;
}

class MiniObservable<T> {
  private readonly producer: (observer: Observer<T>) => Teardown;

  constructor(producer: (observer: Observer<T>) => Teardown) {
    this.producer = producer;
  }

  subscribe(observer: Partial<Observer<T>>): () => void {
    let closed = false;
    let teardown: Teardown;
    const safe: Observer<T> = {
      next: (v) => !closed && observer.next?.(v),
      error: (e) => {
        if (!closed) {
          closed = true;
          observer.error?.(e);
          if (teardown) teardown();
        }
      },
      complete: () => {
        if (!closed) {
          closed = true;
          observer.complete?.();
          if (teardown) teardown();
        }
      },
    };
    teardown = this.producer(safe);
    return () => {
      if (!closed) {
        closed = true;
        if (teardown) teardown();
      }
    };
  }

  pipe<R>(op: (source: MiniObservable<T>) => MiniObservable<R>): MiniObservable<R> {
    return op(this);
  }
}

function map<T, R>(fn: (v: T) => R) {
  return (source: MiniObservable<T>) =>
    new MiniObservable<R>((subscriber) => {
      const unsubscribe = source.subscribe({
        next: (v) => subscriber.next(fn(v)),
        error: (e) => subscriber.error(e),
        complete: () => subscriber.complete(),
      });
      return unsubscribe; // cancelling the outer subscription cancels the source
    });
}

const ticks = new MiniObservable<number>((observer) => {
  let n = 0;
  const id = setInterval(() => observer.next(++n), 10);
  return () => {
    clearInterval(id);
    console.log('source torn down');
  };
});

const cancel = ticks.pipe(map((n) => n * 10)).subscribe({ next: (v) => console.log('value', v) });
setTimeout(() => {
  cancel();
  console.log('unsubscribed');
}, 35);

TypeScript 5.8. The script was run in Node 24 twice with identical output. It is a teaching model, not RxJS code.

Key points

  • An Observable wraps a producer function that receives a subscriber and returns a teardown.
  • Nothing runs until `subscribe`. Each subscribe runs the producer again.
  • An operator wraps a source in a new Observable. Teardowns chain back to the source.
  • The contract: no values after `complete` or `error`, teardown runs once.

Common mistakes

  • Believing an Observable runs when it is created.
  • Forgetting that a custom operator must return the inner teardown.
  • Emitting after `complete` in a hand-written Observable.

Follow-ups

  • How does `switchMap` manage the inner subscription?
  • Why is `of(1,2,3)` synchronous?
  • What does the real `Subscriber` class add?

Tips

  • Live-code the `map` operator. It is short and convincing.
  • State the contract rules.
  • Link teardown chains to cancellation in `switchMap`.

Evaluation rubric

  • Explains the producer, subscriber and teardown model.
  • Implements an operator correctly.
  • Connects it to real behaviour such as cancellation and laziness.