RxJs 6

Greetings In this article, we will look at version 6 of the RxJS library, which allows you to apply the reactive programming approach in JavaScript. Keep in mind we will not be focusing on RxJs in angular.

This article assumes that you are familiar with the concept of reactive programming so you should be familiar with streams if not:

Streams are a sequence of values over time, that’s it.

For example a number that goes up by 1 every second might have a stream that looks like

[0,1,2,3,4]

Another stream might be a sequence of x and y positions of mouse click events, like so:

[(12,34), (345,22), (1,993)]

We could even have a stream to represent a user filling in a form on a website.

So, let’s begin!

RxJs is a library that implements reactive programming in javascript.

Think of RxJS as Lodash for events.

To fully realize the power of rxjs, first we will need to understand some key concepts:

  • Observables - An observable represents a stream of data that we can subscribe to. For example:

      import {Observable} from 'rxjs';
    
      const obs = Observable.create((observer) => {
              let count = 0;
              console.log('Observable created');
    
              const timer = setInterval(() => {
                      observer.next(count);
                      count++;
              }, 1000);
    
              return () => {
                      console.log('Observable destroyed');
                      clearInterval(timer);
              }
      });
    

    So what we did here is create an observable that simply counts every second and outputs the current value to the stream, it will only start when we subscribe to our observable source

  • Observer - You will notice that in the above example there is something called an observer. The observer is an interface for a consumer of push-based notifications delivered by an Observable. Every time we call the method next we provide a notification of another value, we should call observer.complete when we are finished with the observer.

  • Subscriptions - A Subscription is an object that represents a disposable resource, usually the execution of an Observable. A Subscription has one important method, unsubscribe, that takes no argument and just disposes the resource held by the subscription.

    To continue our example: const subscription = obs .subscribe((count) => { console.log(count: ${count}) }) The subscribe function returns a subscription. We should unsubsribe to our observable once we are finished with it. Once we subscribe to our observable it will start emitting data. Unlike a promise which runs automatically once created, an observable only starts running once we subscribe to it.

  • Operators - There are two types of operators, Creational and Pipable, Creational operators are operators that can be called as standalone functions to create new observables. Pipable operators are functions that can be “piped” to an observable. They take in an observable as an input and returns another observable as its output. We will mainly focus on the Pipable operators.

    So for example lets modify our subscription to log only prime numbers, to do this we will use the filter operator

      const isPrime = num => {
              for(let i = 2, s = Math.sqrt(num); i <= s; i++)
                      if(num % i === 0) return false; 
              return num > 1;
      }
    
      const subscription = obs
          .pipe(filter(isPrime))
          .subscribe((count) => {
              console.log(`count: ${count}`)
          })
    

    Now our subscription logs only the prime numbers, it will still count every second but only the prime numbers will be printed to the console.

For a more complicated example i create a blog post site using socket.io and rxjs https://github.com/Hodor9898/reactive-blog-rxjs-socketio

To summarize

We covered the basics of rxjs, using pipable operators with observables can be a powerful tool that will make our code more scalable and readable. There are many more operators that rxjs provides like map, combineLatest and many more, for a full list look at the official docs: https://rxjs-dev.firebaseapp.com/guide/operators

Thank you for your interest!

We will contact you as soon as possible.

Send us a message

Oops, something went wrong
Please try again or contact us by email at info@tikalk.com