← Back to JavaScript, page 6

javascript-0109 · Hard senior

How would you build a minimal Observable with map, filter, take, and unsubscribe support?

An Observable is a function that, when subscribed, starts producing values to an observer (next, error, complete) and returns a teardown function. Operators such as map and filter return new Observables that subscribe to the source and transform what passes through. It is lazy and can be cancelled, unlike a Promise, which is eager and delivers one value.

Full answer

An Observable describes a stream of values over time. It does nothing until someone subscribes, and each subscription runs the producer again (a cold observable). It is the model behind RxJS and the proposed standard Observable.

Core pieces:

  • Constructor: takes a subscribe function (observer) => teardown. The function pushes values with observer.next(value), can fail with observer.error(err), and ends with observer.complete(). It may return a cleanup function, for example one that calls clearTimeout or removeEventListener.
  • subscribe(observerOrFn): wraps the observer in a safe object. After error or complete, or after unsubscribe, the wrapper ignores further calls. That guarantee is important. It returns { unsubscribe }, which marks the wrapper closed and runs the teardown.
  • Operators: map(fn) returns new Observable((observer) => source.subscribe({ next: (v) => observer.next(fn(v)), error, complete })). filter calls next only if the predicate passes. take(n) completes after n values and unsubscribes from the source. Each operator returns the inner subscription's unsubscribe as its teardown, so cancelling the end of the chain cancels the start.
  • pipe(...operators) applies functions from left to right.

Compared with a Promise: an Observable can emit many values, is lazy, can be cancelled, and supports operators for composition. A Promise is eager, resolves once, and cannot be cancelled. Compared with an event emitter: the Observable composes with operators and has a clean completion and cleanup contract.

For production code, use RxJS, which also handles error propagation inside operators, schedulers, subjects for multicasting, and many more operators such as switchMap and debounceTime.

javascript
class Observable {
  constructor(producer) {
    this.producer = producer;
  }

  subscribe(observer) {
    const target = typeof observer === 'function' ? { next: observer } : observer;
    let closed = false;
    let teardown;
    const safe = {
      next: (value) => { if (!closed) target.next?.(value); },
      error: (error) => { if (!closed) { closed = true; target.error?.(error); teardown?.(); } },
      complete: () => { if (!closed) { closed = true; target.complete?.(); teardown?.(); } },
    };
    teardown = this.producer(safe);
    if (closed) teardown?.();
    return { unsubscribe() { closed = true; teardown?.(); } };
  }

  pipe(...operators) {
    return operators.reduce((source, operator) => operator(source), this);
  }
}

const map = (fn) => (source) =>
  new Observable((observer) =>
    source.subscribe({ next: (v) => observer.next(fn(v)), error: observer.error, complete: observer.complete }).unsubscribe);

const filter = (predicate) => (source) =>
  new Observable((observer) =>
    source.subscribe({ next: (v) => predicate(v) && observer.next(v), error: observer.error, complete: observer.complete }).unsubscribe);

const take = (count) => (source) =>
  new Observable((observer) => {
    let seen = 0;
    const subscription = source.subscribe({
      next: (v) => {
        if (seen++ < count) observer.next(v);
        if (seen >= count) observer.complete();
      },
      error: observer.error,
      complete: observer.complete,
    });
    return subscription.unsubscribe;
  });

const fromArray = (items) => new Observable((observer) => {
  items.forEach((item) => observer.next(item));
  observer.complete();
});

const timer = (ms, count) => new Observable((observer) => {
  let n = 0;
  const id = setInterval(() => {
    observer.next(n++);
    if (n === count) observer.complete();
  }, ms);
  return () => {
    clearInterval(id);
    console.log('timer cleaned up');
  };
});

fromArray([1, 2, 3, 4, 5, 6])
  .pipe(filter((n) => n % 2 === 0), map((n) => n * 10))
  .subscribe({ next: (v) => console.log('value', v), complete: () => console.log('array done') });

const cold = fromArray([1, 2]).pipe(map((n) => n + 1));
cold.subscribe((v) => console.log('first subscriber', v));
cold.subscribe((v) => console.log('second subscriber', v));

timer(10, 100)
  .pipe(take(3))
  .subscribe({ next: (v) => console.log('tick', v), complete: () => console.log('take(3) complete') });

const sub = timer(10, 100).subscribe(() => {});
sub.unsubscribe();

Run with Node.js v24.22.1 as js-109.js; two runs gave identical output. Output: value 20 value 40 value 60 array done first subscriber 2 first subscriber 3 second subscriber 2 second subscriber 3 timer cleaned up tick 0 tick 1 tick 2 take(3) complete timer cleaned up

Key points

  • An Observable wraps a subscribe function that pushes next, error, and complete and returns a teardown.
  • It is lazy and cold: each subscription starts the producer.
  • The subscriber wrapper ignores calls after complete, error, or unsubscribe.
  • Operators return new Observables that subscribe to their source and pass the teardown down the chain.
  • Unlike Promises, Observables emit many values and can be cancelled.

Common mistakes

  • Not stopping the producer on unsubscribe, which leaves timers and listeners running.
  • Letting values pass after complete or error.
  • Treating an Observable as eager like a Promise.
  • Forgetting that each subscription runs the producer again.

Follow-ups

  • What is the difference between a cold and a hot Observable, and how does a Subject make one hot?
  • How would switchMap cancel a previous inner request?
  • When would you choose an Observable over async iterators?

Tips

  • Explain laziness and teardown first; they are the point of the design.
  • Show one operator and say that all others follow the same shape.
  • Compare with Promises and event emitters in one sentence each.