dcsimg
December 14, 2019
Hot Topics:

Writing Reactive Code with RxJS

  • March 22, 2019
  • By Robert Gravelle
  • Send Email »
  • More Articles »

RxJS is a JavaScript library that brings "reactive programming" to your Web apps. Reactive programming describes a way to "react" to changes that occur in your application; for instance, click events, or asynchronous data fetching. Unlike other ways of handling asynchronous events, such as promises, RxJS's Observable sequences are cancellable, and can also be easily chained, manipulated, and configured. The goal of today's article will be to get a taste of reactive programming, as well as what RxJS can do.

The Promise of Promises

Here's a promise that prints a message to the console after 2 seconds. To make that work, we pass a function to the Promise the constructor will provide a reference to a resolve function via a function parameter. By using this special resolver function, we can forward the value to the resolve for the consumer of our promise to receive the value once our process completes.

const promise = new Promise(resolve => {
   setTimeout(() => {
      resolve('Hello from a Promise!');
   }, 2000);
});

promise.then(value => console.log(value));

In complex applications, Promises can break down. For example, if we wanted to process multiple async values or events, say from a WebSocket.

RxJS Observables

Observables are not part of the JavaScript spec yet, so we need to employ the RxJS library. It provides an Observable implementation to use as well as many helpful utilities related to Observables.

Here's some code that demonstrates the exact same functionality as our Promise example above:

const observable = new Rx.Observable(observer => {
   setTimeout(() => {
      observer.next('Hello from an Observable!');
   }, 2000);
});
observable.subscribe(value => console.log(value));

Just like last time, we pass a function that will handle our async task to the constructor. In the Observable function, we can create a setTimeout just as we did in our Promise example. Once we're done our work, we call observer.next() to trigger and emit our value to the consumer of our Observable. The Observable then will pass us a reference to an object called an Observer. The Observer, in turn, has a method called subscribe(). It listens for data from the observer.

Handling DOM Events

Observables can also respond to DOM events. The fromEvent() method accepts a DOM element and event name. It then returns an observable that you can consume. Here's an observable that sends out the time that a DIV was clicked:

// Create observable that emits click events
const doc = Rx.Observable.fromEvent(document.getElementById
   ('clickDiv'), 'click');
// Map to string with given event timestamp
const timestamp = doc.map(event => `Event time: ${event.timeStamp}`)
// Output (example): 'Event time: 7276.390000000001'
const subscribe = timestamp.subscribe(val => console.log(val));

Observing Data Over Time

One of the significant differences between Observables and Promises is that, whereas a Promise completes once it has resolved its async value, Observables are able to emit multiple values over time. Some common use cases are to push notifications, relay user input changes, or broadcast repeating intervals.

Our final example is going to show how to create an Observable, just like our previous example, but instead of using setTimeout(), we will use a Observable.interval() to show multiple values—one every second:

const multiple = Rx.Observable.fromEvent(document.getElementById
   ('multiple'), 'click');
const interval = Rx.Observable.interval(1000);
multiple.subscribe(val => {
   interval.take(5).subscribe(value => console.log(value));
});

That will print 0, 1, 2, 3, 4, 5 to the console.

Conclusion

RxJS is actually a huge library. It provides methods for doing just about anything that you could ever imagine doing with Observables and probably a few things that you never imagined!

You can see all of the examples presented here on Codepen.







Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.


Thanks for your registration, follow us on our social networks to keep up-to-date