Observable API
Observable API
Observable API
The **Observable API** provides a mechanism for handling streams of values, including asynchronous events. You can declare a pipeline to filter and transform these values, subscribe to receive them, and unsubscribe when they are no longer needed.
## Concepts and usage
### Events and reactive programming
Events are fundamental to web development and JavaScript programming at large. Events originate from EventTarget objects:
```js
element.addEventListener("click", handler1);
element.addEventListener("click", handler2);
```
When the user clicks on the `element`, the element, controlled by the browser, is responsible for pushing a notification to each of its event listeners, which are `handler1` and `handler2` in this case. The notification is an Event object providing further context and data about the event. The handler then carries out some action in response to the event.
This paradigm is known as _reactive programming_, where actions are carried out passively in response to a trigger. Abstractly, there are four main kinds of reactive programming:
- _Single pull_: The initiator receives a single value. Normal functions implement this: in `const result = action();`, the caller of the `action()` function is the initiator, which pulls a single value `result` from the function.
- _Single push_: The initiator sends a single value, and the receiver waits before it receives that value. [Promises](/docs/Web/JavaScript/Reference/Global_Objects/Promise) implement this: in `promise.then((value) => { ... });`, the promise implementation is the initiator, which calls the callback function exactly once when the promise is fulfilled, sending a single value.
- _Multiple pulls_: The initiator pauses and resumes execution of the data source, eventually receiving multiple values. [Iterators](/docs/Web/JavaScript/Reference/Iteration_protocols) implement this: in `const result1 = iterator.next(); const result2 = iterator.next();`, the caller of the `next()` method is the initiator, which pulls multiple values from the iterator.
- _Multiple pushes_: The initiator sends multiple values, and the receiver pauses execution in between receiving those values. Events implement this: in `element.addEventListener("click", handler);`, the element is the initiator, which calls the `handler` function multiple times as the user clicks on the element, sending multiple event objects.
### Composing event streams
The problem with the `addEventListener()` model is that there's no neat way to _compose_ event handlers. Each handler is executed in isolation and doesn't inherently have knowledge about the other events in a sequence. For example, if you want to do something specifically for a `mousemove` event that happens after a `mousedown` event, you have to manage any shared state yourself, leading to complex and fragile code.
The Observable API addresses this problem by declaratively creating and manipulating streams of events using methods such as Observable.map() and Observable.filter(). It doesn't fundamentally replace the event-driven model, but rather changes the way you organize your code, much like how promises changed the way asynchronous code is written compared to traditional callbacks.
> [!NOTE]
> The Observable API is not inherently related to the event API. While event handling is a major use case for observables, observables can represent any stream of data, not just events. Because of this, the observable API is actually more like a language primitive than a web-exclusive API, just like Promise or Iterator. It is specified outside of TC39 for historical reasons, like AbortController or [streams](/docs/Web/API/Streams_API).
### Obtaining observables
In the Observable API, an **observable** represents a stream of values, and an **observer** receives its notifications through callbacks. The code that sends values is called the _producer_, while the code that makes use of these values is called the _consumer_. You typically write the consumer code by using methods on the Observable interface to transform and consume values from observables. If you are the implementor of an observable, you write the producer code by using the Subscriber interface to send values to the observers. There are three main ways to obtain observables:
- The EventTarget.when() method returns an Observable representing a stream of events fired on the `EventTarget`. You may also have libraries that return observables.
- You can create your own custom observables using the Observable() constructor.
- You can convert objects such as [promises](/docs/Web/JavaScript/Reference/Global_Objects/Promise) and [iterables](/docs/Web/JavaScript/Reference/Iteration_protocols) into observables using the static Observable.from() method.
### Transforming, subscribing, and unsubscribing
An observable can be transformed using various methods that return new observables, such as Observable.map() and Observable.filter().
To start receiving values from an observable, you subscribe to it using the Observable.subscribe() method, or aggregate all values using [promise-returning methods](/docs/Web/API/Observable#promise-returning_instance_methods) like Observable.reduce(). Observables are _lazy_ — they don't start producing values until they have at least one subscriber.
You can also unsubscribe from an observable using an AbortController or certain methods like Observable.takeUntil().
Let's consider a brief example:
```js
document.body
.when("mousedown")
.filter((e) => e.target.matches("body"))
.map((e) => ({ x: e.clientX, y: e.clientY }))
.subscribe((p) => {
console.log(`${p.x},${p.y}`);
});
```
In this snippet, the page's body element is an EventTarget. We obtain a stream of [`mousedown`](/docs/Web/API/Element/mousedown_event) events fired on it using the `when()` method.
We then specify a pipeline:
- Observable.filter() filters the events passed through the pipeline to only events fired on the body element (tested using the Element.matches() method) and not its descendants.
- Observable.map() maps the fired `mousedown` event objects to new objects containing the coordinates of the mouse cursor when the event was fired.
- Observable.subscribe() subscribes to the observable. Its callback logs the mouse coordinates to the console each time a `mousedown` event passes the filter.
You may notice that this paradigm is very similar to [iterators](/docs/Web/JavaScript/Reference/Iteration_protocols), where we can also transform with [`map()`](/docs/Web/JavaScript/Reference/Global_Objects/Iterator/map) and [`filter()`](/docs/Web/JavaScript/Reference/Global_Objects/Iterator/filter) and consume with `next()` and [`toArray()`](/docs/Web/JavaScript/Reference/Global_Objects/Iterator/toArray). Indeed, both observables and iterators represent streams of data; the key difference, as previously stated, is that iterators are pull-based (the consumer decides when to receive values), while observables are push-based (the producer decides when to send values).
See [Using observables](/docs/Web/API/Observable_API/Using_observables) and [Creating custom observables](/docs/Web/API/Observable_API/Creating_observables) for more information on the above concepts.
## Interfaces
- Observable
- : Represents a stream of values that can be subscribed to.
- Subscriber
- : Represents a subscription to a stream of observable values, and contains methods to manage the lifecycle of that subscription.
## Extensions to other interfaces
- EventTarget.when()
- : Returns an observable representing a stream of events that will be fired on the `EventTarget`.
## Examples
See [Using observables](/docs/Web/API/Observable_API/Using_observables) and [Creating custom observables](/docs/Web/API/Observable_API/Creating_observables) for complete examples.
## Specifications
## Browser compatibility
## See also
- [Observable explainer](https://github.com/WICG/observable/blob/master/README.md)
Cite this
"Observable API". MDN Web Docs. CC BY-SA 2.5 (MDN). https://developer.mozilla.org/en-US/docs/Web/API/Observable_API