# Observables compared to other techniques
You can often use observables instead of promises to deliver values asynchronously. Similarly, observables can take the place of event handlers. Finally, because observables deliver multiple values, you can use them where you might otherwise build and operate on arrays.
Observables behave somewhat differently from the alternative techniques in each of these situations, but offer some significant advantages. Here are detailed comparisons of the differences.
## Observables compared to promises
Observables are often compared to promises. Here are some key differences:
* Observables are declarative; computation does not start until subscription. Promises execute immediately on creation. This makes observables useful for defining recipes that can be run whenever you need the result.
* Observables provide many values. Promises provide one. This makes observables useful for getting multiple values over time.
* Observables differentiate between chaining and subscription. Promises only have `.then()` clauses. This makes observables useful for creating complex transformation recipes to be used by other part of the system, without causing the work to be executed.
* Observables `subscribe()` is responsible for handling errors. Promises push errors to the child promises. This makes observables useful for centralized and predictable error handling.
### Creation and subscription
* Observables are not executed until a consumer subscribes. The `subscribe()` executes the defined behavior once, and it can be called again. Each subscription has its own computation. Resubscription causes recomputation of values.
// declare a publishing operation
new Observable((observer) => { subscriber_fn });
// initiate execution
observable.subscribe(() => {
// observer handles notifications
});
* Promises execute immediately, and just once. The computation of the result is initiated when the promise is created. There is no way to restart work. All `then` clauses (subscriptions) share the same computation.
// initiate execution
new Promise((resolve, reject) => { executer_fn });
// handle return value
promise.then((value) => {
// handle result here
});
### Chaining
* Observables differentiate between transformation function such as a map and subscription. Only subscription activates the subscriber function to start computing the values.
observable.map((v) => 2*v);
* Promises do not differentiate between the last `.then` clauses (equivalent to subscription) and intermediate `.then` clauses (equivalent to map).
promise.then((v) => 2*v);
### Cancellation
* Observable subscriptions are cancellable. Unsubscribing removes the listener from receiving further values, and notifies the subscriber function to cancel work.
const sub = obs.subscribe(...);
sub.unsubscribe();
* Promises are not cancellable.
### Error handling
* Observable execution errors are delivered to the subscriber's error handler, and the subscriber automatically unsubscribes from the observable.
obs.subscribe(() => {
throw Error('my error');
});
* Promises push errors to the child promises.
promise.then(() => {
throw Error('my error');
});
### Cheat sheet
The following code snippets illustrate how the same kind of operation is defined using observables and promises.
|
Observable |
Events API |
Creation & cancellation |
// Setup
let clicks$ = fromEvent(buttonEl, ‘click’);
// Begin listening
let subscription = clicks$
.subscribe(e => console.log(‘Clicked’, e))
// Stop listening
subscription.unsubscribe();
|
function handler(e) {
console.log(‘Clicked’, e);
}
// Setup & begin listening
button.addEventListener(‘click’, handler);
// Stop listening
button.removeEventListener(‘click’, handler);
|
Subscription |
observable.subscribe(() => {
// notification handlers here
});
|
element.addEventListener(eventName, (event) => {
// notification handler here
});
|
Configuration |
Listen for keystrokes, but provide a stream representing the value in the input.
fromEvent(inputEl, 'keydown').pipe(
map(e => e.target.value)
);
|
Does not support configuration.
element.addEventListener(eventName, (event) => {
// Cannot change the passed Event into another
// value before it gets to the handler
});
|
## Observables compared to arrays
An observable produces values over time. An array is created as a static set of values. In a sense, observables are asynchronous where arrays are synchronous. In the following examples, ➞ implies asynchronous value delivery.
|
Observable |
Array |
Given |
obs: ➞1➞2➞3➞5➞7
obsB: ➞'a'➞'b'➞'c'
|
arr: [1, 2, 3, 5, 7]
arrB: ['a', 'b', 'c']
|
concat() |
obs.concat(obsB)
➞1➞2➞3➞5➞7➞'a'➞'b'➞'c'
|
arr.concat(arrB)
[1,2,3,5,7,'a','b','c']
|
filter() |
obs.filter((v) => v>3)
➞5➞7
|
arr.filter((v) => v>3)
[5, 7]
|
find() |
obs.find((v) => v>3)
➞5
|
arr.find((v) => v>3)
5
|
findIndex() |
obs.findIndex((v) => v>3)
➞3
|
arr.findIndex((v) => v>3)
3
|
forEach() |
obs.forEach((v) => {
console.log(v);
})
1
2
3
5
7
|
arr.forEach((v) => {
console.log(v);
})
1
2
3
5
7
|
map() |
obs.map((v) => -v)
➞-1➞-2➞-3➞-5➞-7
|
arr.map((v) => -v)
[-1, -2, -3, -5, -7]
|
reduce() |
obs.scan((s,v)=> s+v, 0)
➞1➞3➞6➞11➞18
|
arr.reduce((s,v) => s+v, 0)
18
|