The publish/subscribe model separates producing data from consuming it. A publisher emits values, while subscribers receive notifications without directly managing the publisher’s work. In stream programming, data flows one way from a source through optional transformations to subscribers. section 9.4 section 9.3.2
The model changes how application code responds to data:
- Pushes new values to subscribers instead of requiring consumers to poll a data structure. section 9.3.2
- Supports synchronous or asynchronous data and can represent sources such as arrays, generators, and other streams. section 9.4 section 9.6
- Allows declarative, lazy pipelines when implemented with observables; execution begins when a subscriber subscribes. section 9.4
A push-enabled array
A PushArray can emit a new-value event from push, expose subscribe({ next }) for consumers, and remove listeners through unsubscribe(). The producer invokes next(value); subscribers do not repeatedly inspect the array for changes. section 9.3.2
Listing 9.12 Subclass of Array that fires events when a new elements is pushed
class PushArray extends Array {
static EVENT_NAME = 'new_value';
#eventEmitter = new EventEmitter();
constructor(...values) {
super(...values);
}
push(value) {
this.#eventEmitter.emit(PushArray.EVENT_NAME, value); #1
return super.push(value);
}
subscribe({ next }) { #2
this.#eventEmitter.on(PushArray.EVENT_NAME, value => {
next(value) #3
});
}
unsubscribe() { #4
this.#eventEmitter.removeAllListeners(PushArray.EVENT_NAME);
}
}
const pushArray = new PushArray(1, 2, 3);
pushArray.subscribe({
next(value) {
console.log('New value:', value)
// do something with value
}
});
pushArray.push(4); #5
pushArray.push(5); #5
pushArray.unsubscribe(); #6
pushArray.push(6); #7
Inspect the complete PushArray listing, including event emission, subscription, unsubscription, and a subscriber that handles each new value. section 9.3.2




