liveBook · Manning

Symbol.observable

As explained in The Joy of JavaScript

A well-known JavaScript symbol proposed for defining how an object converts to or exposes an observable representation.

Symbol.observable is a proposed well-known JavaScript symbol for defining how an object becomes, or exposes, an Observable. Observable.from invokes the symbol when present, wrapping the returned value as an Observable when necessary. section 9.4.7

The protocol lifts ordinary objects into stream programming, allowing them to use composition, operators, declarative APIs, subscription, and observable error handling. Without the symbol, Observable.from falls back to interpreting the argument as an iterable and emits its values synchronously during subscription. section 9.4.7

Implementations follow these rules:

  • Define [Symbol.observable]() to return an Observable representation. section 9.4.7
  • Emit existing values when subscription begins, then emit future values when the object is dynamic. section 9.4.7 section 9.4.8
  • Manage unsubscription explicitly for infinite streams that never call observer.complete. section 9.4.7

A Pair as an Observable

A Pair object can expose an Observable that emits its left and right values and then completes: Pair(20, 30) becomes consumable through Observable.from(Pair(20, 30)).

Dynamic objects as streams

A Blockchain can emit its existing blocks during subscription and notify subscribers whenever push adds another block. A subscriber can validate each block and later call unsubscribe; a reactive array can similarly feed values through filter and map after arr$.push(6).

How The Joy of JavaScript covers it

How deep it goes
Explains protocol semantics and demonstrates adapters, event emission, replay, completion, and unsubscription, while stopping short of comprehensive observable coverage.
Examples
Uses Pair, Blockchain, reactive arrays, push interception, filtering, mapping, block validation, logging, and explicit unsubscription.
What it assumes
Assumes familiarity with iterables, symbols, Observable subscriptions, push protocols, event emitters, and basic stream operators.
What you can do after
Build an Observable adapter for finite or dynamic objects and consume it through Observable.from and subscriptions.
How it connects
Ties Symbol.observable to Observable.from, iterables, EventEmitter, Proxy, subscription, operators, and cold and hot observables.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Joy of JavaScript. The section links point to the parts of the book it draws on.