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.
classObservable {constructor(subscriber) // subscriber(observer) may return a teardown functionsubscribe(observerOrNext) // returns { unsubscribe() }map(project) // returns a new Observable; project(value, index)filter(predicate) // returns a new Observable; predicate(value, index)staticof(...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.
The constructor throws a TypeError when subscriber is not a function. It does not call it.
Each subscribe calls subscriber once, at once, with a new observer. Two subscriptions never share values.
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.
After complete, error or unsubscribe, the subscription is closed: nothing more is delivered, and observer.closed is true (it is false before).
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.
If subscriber throws, the error goes to the observer's error.
An error with no error handler is reported with reportError(error), not thrown.
The observer's functions work when detached from it (for example passed to setTimeout).
Observable.of(...values) sends each value in order, then completes.
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.
Unsubscribing from a map or filter result unsubscribes from its source.
If project or predicate throws, the error is sent on, the source is unsubscribed, and the function is not called again.
map and filter throw a TypeError when not given a function.
newObservable((observer) => { observer.complete(); observer.next("ignored");return () => console.log("cleaned up");}).subscribe(() => {});// "cleaned up": complete came before the teardown was returned
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.