Simple Observable
HardDesign Patterns25 min4 tests
Implement a simple Observable class with subscribe, next, complete, and unsubscribe functionality.
Requirements
subscribe(observer)— register an observer withnextand optionalcompletecallbacks. 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)
- Use a Set to store subscribers for easy add/delete.
- subscribe should return an unsubscribe function that removes the observer from the Set.
- next iterates over all subscribers and calls their
nextmethod. - complete should set a flag, call all subscriber
completecallbacks, then clear the Set.
Topics
- Design Patterns
Asked at
Netflix · Google · Uber
