loading...
Cover image for Intro to Observables with RxJS
Netguru

Intro to Observables with RxJS

sebhewelt profile image Sebastian Hewelt Updated on ・5 min read

At first, I had a hard time trying to find any reliable resource on RxJS (besides the docs), which wouldn't treat it in the context of Angular. There is much less talk online about integrating RxJS with React or Vue. Then, I learned that since Angular 2 the framework relies heavily on RxJS, and that's probably why. Turns out though, it works perfectly fine with any other widely used framework, like React or Vue, too! This article though, focuses on RxJS and observables in general, without going into peculiarities of any frontend framework.

What is RxJS?

RxJS [or ReactiveX] is a library for reactive programming using Observables, to make it easier to compose asynchronous or callback-based code.

~ RxJS docs

Be aware, that there are implementations of Rx for other platforms too. There is RxJava, RxPHP, RxSwift and many others. The newest stable version of RxJS is v6. v7 is currently in alpha, so we may see it released as a stable version soon.

The theory (just a little)

The fundamental concept and the core of RxJS that we need go through, in order to better understand RxJS, is the concept of an observable. So what is an observable? In shortest terms it's data arriving over time. It comes from the observer pattern, a software design pattern that addresses the problem of automatically updating UIs when events occur. It's also sometimes called a stream. Although stream is a broader term, if you've heard about it in the RxJS context, it most likely refers to the same thing. So, observable === stream. You can subscribe to Observables with subscribers (also called observers, so subscribers === observers). A subscriber is just an object which triggers three actions upon events, next, error or complete:

    // A subscriber example

    {
    next: event => console.log(`Hey, this is ${event}.`), 
    error: error => console.log(`Oh no, ${error}.`),
    complete: () => console.log(`Now I'm complete`), 
    }

next controls the flow of events, reacting to them. error and complete are two ways of terminating the stream, which no longer emits data when any of those two happen. The difference is, complete doesn't get passed any value to it.

To put those concepts together, here's an Observable with a subscriber:

    // An Observable example with two subscriptions to the same Observable.

    import { Observable } from 'rxjs';

    const foo = new Observable(subscriber => {
      console.log('Hello');
      subscriber.next(42);
    });

    foo.subscribe(x => {
      console.log(x);
    });
    foo.subscribe(y => {
      console.log(y);
    });

    // "Hello"
    // Hey, this is 42.
    // "Hello"
    // Hey, this is 42.

The glossary of RxJS-related concepts includes also:

Subject - type of an observable. Observable and observer combined.
Event - a mouse click, a scroll, a route change, a request
Operators - They are predefined set of functions RxJS exposes, so you can manipulate values from a source with them, returning an observable of the transformed values. You import them similar to as you would import a util from Lodash or Ramda. But the comparison to Ramda is more accurate, because of its composable nature.
Example: import { map, filter } from 'rxjs/operators';

Why is it so cool?

It helps managing the control flow of many async data requests

In the old pre-ES2015 days of web development, asynchronous operations in javascript were mostly handled with callbacks. The major drawback of callbacks was the so called "callback hell", where you would nest functions deeply in one another, to be executed when its wrapping function is done. It would lead to a spaghetti code with a series of ))}})} at the end of blocks. Modern vanilla javascript uses Promise API to solve asynchronous problems. There's also async/await, but it's also Promise under the hood, just with cleaner syntax. Promises functionality is limited, though. Both Promises and Observables are push collections. But, and here's the important part, Promises operate on a single value. You create one, possibly provide a .then() that gets passed a value as soon as the Promise settles, and that's it. It's "bound" to this single value. What's more, a Promise cannot be cancelled. Observable on the other hand, can hold multiple values and the action performed upon it can be easily cancelled. For more head over to official docs which describe more differences between an Observable and a Promise.

Where does RxJS shine the most?

There are no restrictions or limitations on how and when to use RxJS. You could add it just for the sake of having a gentle ending of loading state toggle when some data arrives. But there are certain types of apps, where RxJS shines the most. Those would be all the apps that need real-time updates, relying on dynamic data. All the dashboard-centric apps, with many widgets and data from many sources, dependent on each other, or where sequence of events is important. These would be the ones where the declarative and sequential nature of the library come in handy. If you're building an app with many asynchronous requests and complex side effects this is the way to go.

Who uses RxJS?

When you browse online you can find evidence that RxJS is widely used as a dependency in many major companies like Microsoft, Github or Netflix. I'd say the last one popularizes RxJS the most recently, providing many video resources, even one on how does Netflix use RxJS internally.

Beware. It's not (yet) a part of javascript

RxJS brings observables objects to javascript. This is because Observables aren't currently a part of the language itself. You install it as a dependency. There is a proposal to add it to javascript, but it's still a Stage 1 proposal. Stage 1 is the second step (0-based index) of four stages in total, which every new feature of javascript needs to go through before being added to the standard. Current status of the proposal means, to quote the TC39 repo, that it represents problems that the committee is interested in spending time exploring solutions to. So nobody really knows, if Observables are going to be a part of ECMAScript 2021 or ECMAScript 2029, or will a completely different solution be developed to solve asynchronicity problems in JS.

src: RxJS Official Docs, https://rxjs-dev.firebaseapp.com/.

Netguru

Netguru builds software that lets people do things differently.

Discussion

pic
Editor guide