To Observableland
To Observableland
Let's depart promiseland and head toward the vast land of Observables.
To prepare for our journey, let's look at a simple event listener in JavaScript.
document.addEventListener('click', () => console.log('💥'));
Here we are adding an event listener to the document that will invoke the callback function when clicked.
Let's create the same event "stream" using an Observable.
import { fromEvent } from 'rxjs';
const observable = fromEvent(document, 'click');
observable.subscribe(() => {
console.log('💥');
});
See the example on codesandbox
Let's review:
- First, we import the
fromEvent()function from therxjsdependency. - The first parameter is the
targetto attach the event listener to. - The second parameter is the
eventName, in this case, theclickevent. - The
fromEvent()function returns a newObservableinstance. - While promises have a
then()method, an Observable has asubscribe()method. - The
subscribe()invokes the execution of the Observable and "listens" for values that are produced. - The
subscribe()function accepts anextcallback function that is invoked with the value. - In this example, when the Observable produces a value, we are simply logging to the console.