LiveLoveApp logo

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 the rxjs dependency.
  • The first parameter is the target to attach the event listener to.
  • The second parameter is the eventName, in this case, the click event.
  • The fromEvent() function returns a new Observable instance.
  • While promises have a then() method, an Observable has a subscribe() method.
  • The subscribe() invokes the execution of the Observable and "listens" for values that are produced.
  • The subscribe() function accepts a next callback function that is invoked with the value.
  • In this example, when the Observable produces a value, we are simply logging to the console.