Skip to curriculum
Jump to the editor

19.3. An observable with map and filter

Hard
Topics
35–60 min

A search box produces keystrokes, a socket produces messages, a timer produces ticks. An observable gives all of them one shape: a function that, when someone subscribes, starts sending values to an observer, and can be stopped. Because nothing runs until a subscribe, observables can be transformed with map and filter before any work starts, the way arrays are, but over time.

Write the class Observable in observable.js.

Signature

JAVASCRIPT
class Observable {
  constructor(subscriber)         // subscriber(observer) may return a teardown function
  subscribe(observerOrNext)       // returns { unsubscribe() }
  map(project)                    // returns a new Observable; project(value, index)
  filter(predicate)               // returns a new Observable; predicate(value, index)
  static of(...values)            // returns a new Observable
}
  • The observer given to subscriber has next(value), error(error), complete() and a closed property.
  • observerOrNext is a function (it handles each value) or an object with any of next, error and complete. It may be missing.

Requirements

  1. The constructor throws a TypeError when subscriber is not a function. It does not call it.
  2. Each subscribe calls subscriber once, at once, with a new observer. Two subscriptions never share values.
  3. A function passed to subscribe receives each value. An object's next, error and complete are called as its methods (this is the object); missing handlers are skipped; subscribe() with no argument works.
  4. After complete, error or unsubscribe, the subscription is closed: nothing more is delivered, and observer.closed is true (it is false before).
  5. The teardown function returned by subscriber runs exactly once: on unsubscribe, after complete, or after error, whichever comes first. If the subscription closed before subscriber returned, the teardown runs as soon as it is returned.
  6. If subscriber throws, the error goes to the observer's error.
  7. An error with no error handler is reported with reportError(error), not thrown.
  8. The observer's functions work when detached from it (for example passed to setTimeout).
  9. Observable.of(...values) sends each value in order, then completes.
  10. map(project) and filter(predicate) return new observables that do nothing until subscribed. Each of their subscriptions subscribes to the source once, with its own index counting from 0. complete and error pass through.
  11. Unsubscribing from a map or filter result unsubscribes from its source.
  12. If project or predicate throws, the error is sent on, the source is unsubscribed, and the function is not called again.
  13. map and filter throw a TypeError when not given a function.

Examples

JAVASCRIPT
const ticks = new Observable((observer) => {
  let n = 0;
  const id = setInterval(() => observer.next(n++), 1000);
  return () => clearInterval(id);
});

const sub = ticks
  .filter((n) => n % 2 === 0)
  .map((n) => "tick " + n)
  .subscribe((text) => console.log(text));
// "tick 0" at 1 s, "tick 2" at 3 s, "tick 4" at 5 s...
sub.unsubscribe();   // the interval is cleared
JAVASCRIPT
Observable.of(1, 2, 3).subscribe({
  next: (value) => console.log(value),
  complete: () => console.log("done"),
});
// 1, 2, 3, "done"
JAVASCRIPT
new Observable((observer) => {
  observer.complete();
  observer.next("ignored");
  return () => console.log("cleaned up");
}).subscribe(() => {});
// "cleaned up": complete came before the teardown was returned

Environment

  • Plain JavaScript in a browser page; the tests use the global class Observable from observable.js.
  • Timer tests run on a virtual clock that replaces setTimeout.
  • Errors thrown by an observer's own handlers, other operators, schedulers and sharing one subscription between subscribers are not part of this problem.

Hints

  1. Which variables must every one of next, error, complete and unsubscribe see, and where can they live so each subscription has its own?
  2. When complete is called inside subscriber, the teardown does not exist yet. When does it?
  3. Inside map, what is this, and when should the source be subscribed?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…