An Observable represents a lazy, one-way flow of values from a source to a subscriber. It provides a consistent way to handle events whether values arrive synchronously or asynchronously. Calling subscribe starts the flow; until then, the Observable is an inert description of it. section 9.4.1 section 9.6
A Promise delivers one eventual result. An Observable can deliver a sequence: messages in a chat, DOM events, response chunks, or values from an array. Unlike repeatedly polling for new messages, a push source notifies subscribers when data is available. An Observable can wrap a Web Stream, but the two are not the same API. section 9.0 section 9.4.1
Subscribe and release
Observable.of('The', 'Joy', 'of', 'JavaScript').subscribe({ next: word => console.log(word) }) sends each word to the observer’s next method. An observer may also define error and complete. subscribe returns a Subscription whose unsubscribe method stops delivery; for a timer-backed source, cleanup can clear the interval. section 9.4.1
To create a source, pass the Observable constructor a function that receives an observer. The function can call observer.next(value) as values become available and return a cleanup function. A timer that emits a random number every second, for example, begins running only on subscription and clears its interval on unsubscription. Observable.of and Observable.from instead lift existing values or data sources. section 9.4.2
Operators transform a flow without changing its source. A map operator subscribes to an upstream Observable, applies a function to each value, and forwards results through a new Observable; it also forwards errors and completion and passes unsubscription upstream. Filter, skip, and reduce can be combined with map to express processing as a pipeline rather than scattering it among callbacks. section 9.4.3
Figure 9.6 The composition of two operators. Three instances of an observable (arrow) are shown: the source observable and two operators. Each operator subscribes to the previous stream and creates a new observable.
The diagram traces a source through two operators, each producing a new Observable by subscribing to the preceding flow. section 9.4.3
A generator can also feed an Observable. One example lifts a generator of file blocks, then skips an initial block, constructs and validates subsequent blocks, filters failures, and reduces the successes to a count. This separates the data source from the processing steps. The Observable API described here was a TC39 proposal, not an assumed built-in JavaScript feature; its proposed skeleton did not supply a built-in operator set. section 9.4.5 section 9.4.3




