In JavaScript, observables are objects that allow you to subscribe to events and receive notifications whenever those events occur. They are a part of the Reactive Programming paradigm and are commonly used in modern front-end frameworks like Angular and React.
Observables are similar to promises in that they both represent a value that may be available at some point in the future. However, observables are more powerful than promises because they can emit multiple values over time, whereas promises only emit a single value.
To use observables in JavaScript, you need to first create an observable object using a library like RxJS. Here's an example of how to create an observable that emits a sequence of numbers:
import { Observable } from 'rxjs';
const observable = new Observable((subscriber) => {
subscriber.next(1);
subscriber.next(2);
subscriber.next(3);
subscriber.complete();
});
In this example, we're creating an observable that emits the numbers 1, 2, and 3 in sequence, and then completes. To subscribe to this observable and receive its values, we can use the subscribe
method:
observable.subscribe({
next: (value) => console.log(value),
complete: () => console.log('Observable completed')
});
In this code, we're subscribing to the observable and passing an object with two methods: next
and complete
. The next
method is called each time the observable emits a value, and the complete
method is called when the observable has completed emitting values.
Observables are a powerful tool for handling asynchronous events in JavaScript, and they can be used in a variety of scenarios, including network requests, user input, and more.
An intro to Observables and how they are different from promises