Simple Observable

HardDesign Patterns25 min4 tests

Implement a simple Observable class with subscribe, next, complete, and unsubscribe functionality.

Requirements

  • subscribe(observer) — register an observer with next and optional complete callbacks. Return an unsubscribe function.
  • next(value) — emit a value to all active subscribers.
  • complete() — notify all subscribers of completion and prevent further emissions.

Example

const obs = new Observable();
const unsub = obs.subscribe({ next: v => console.log(v) });
obs.next('hello'); // logs 'hello'
unsub();
obs.next('world'); // nothing (unsubscribed)
Hints (4)
  1. Use a Set to store subscribers for easy add/delete.
  2. subscribe should return an unsubscribe function that removes the observer from the Set.
  3. next iterates over all subscribers and calls their next method.
  4. complete should set a flag, call all subscriber complete callbacks, then clear the Set.

Topics

  • Design Patterns

Asked at

Netflix · Google · Uber

Join Us
blur