Skip to main content

RxJs

RxJS is an abbreviation for Reactive Extension for JavaScript. In other words, Rxjs is the javascript implementation of Reactive X . It is a javascript library that employs the reactive programming concept in web development. It uses observable sequences to deal with asynchronous data and event-based programmes. It has one core type, the Observable, satellite types (Observer, Schedulers, Subjects), and operators inspired by Array#extras (map, filter, reduce, every, and so on) to handle asynchronous events as collections. RxJS can be used in conjunction with other JavaScript libraries such as Angular, ReactJS, Vue.js, Node.js, and others. It is also compatible with TypeScript.

RxJS is to Javascript as Henry Ford's assembly line was to cars.

What is ReactiveX ?


ReactiveX is an API for asynchronous and event-based programming with observable sequences.It extends the observer pattern to support data and/or event sequences and introduces operators that allow you to compose sequences declaratively while abstracting away concerns about low-level threading, synchronisation, thread-safety, concurrent data structures, and non-blocking I/O.ReactiveX combines the Observer and Iterator patterns, as well as functional programming and collections, to address the need for an ideal method of managing event sequences.

For more details on Reactive X follow this link - Reactive X docs

What is Reactive programming?


Reactive programming is a new way of dealing with data and events. The code in this section responds to any event or change that occurs. When you use reactive programming, your code becomes cleaner and more maintainable.

In reactive programming, everything is viewed as an asynchronous data stream (or async event streams). These streams could consist of UI-events, tweets, video streams, data from sockets, and so on. Assume you've assigned Observers to these streams, and they can respond to any event. Then there are the magic functions for Filtering, Combining, and even reporting errors when they occur.

As you may be aware, data can take many forms, including a stream of data, a stream of events, data from REST API, data from WebSockets, and user events such as mouse clicks, key inputs, and so on. This is referred to as an Observable sequence in Reactive Programming. These Observables can be subscribed to by a function to receive asynchronous data whenever one arrives, and they are Subscribers. The Observer Design Pattern is used in a slightly different way in reactive programming.

For details about reactive programming follow these links -

The introduction to Reactive Programming you've been missing

5 things about reactive programming

What is a Stream ?


A stream is defined as a time-ordered sequence of data or events, such as tweets, mouse events, or socket data. These streams can emit three types of data: a value, an error, or a completed signal. The completed signal indicates that the stream has been completed.

Features of RxJS


In RxJS, following are the essential concepts that handles async event management :

  • Observable: The term observable refers to the concept of an invokable collection of future values or events. It's a function that creates an observer and binds it to the source where values are expected. Clicks, mouse events from a DOM element or an HTTP request, and so on are observable examples.
  • Observer: It is a set of callbacks that specify how to listen for values delivered by the Observable. It can be specified as an object with next() , error() , and complete() methods that will be executed when interacting with the observable.
  • Subscription: It represents the execution of an Observable. Its primary function is to cancel the execution. For example, once an observable is created, you must subscribe to it in order for it to be executed. It is also capable of cancelling the execution.
  • Operators: Operators are pure functions that allow a functional programming style to deal with collections using operations such as map, filter, concat, reduce, etc. It takes an observable as input and returns an observable as output.
  • Subject: A subject is similar to an EventEmitter in that it is used to multicast a value or event to multiple Observers. As an example: Consider a button with an event listener; the function attached to the event via addlistener is called every time the user clicks on the button; similarly, subject has this functionality.
  • Schedulers: Schedulers are centralised dispatchers used to manage concurrency. They are used to control when the subscription should start and be notified. e.g. setTimeout or requestAnimationFrame or others.

Why use Rxjs ?


When your project involves a lot of async task handling, RxJS is the way to go. It is the best option in these circumstances. The Angular project includes RxJS by default.

There are a lot of javascript async libraries JQuery, Async.js, Q.js, or others but it is better to prefer RxJS overall because RxJS will assist you in resolving the following issues by combining the functional and reactive programming paradigms:

  • Since they are not async compatible, the most commonly used control flow structures, such as for and while loops, do not work well with asynchronous functions. As a result, they are oblivious to the amount of time that passes between iterations.

  • When you start nesting try/catch blocks within each callback, error-handling strategies become complicated. From a functional standpoint, RxJS provides an error-handling approach.

  • RxJS provides an ideal and simple mechanism for cancelling events cleanly after a fixed amount of time. Even with the assistance of third-party libraries, implementing your cancellation mechanism can be difficult and error prone.

  • Closures should not be used excessively in programming, but functions in JavaScript create a closure around the scope in which they are declared. When you nest them, you must be concerned about the state of the variables passed in as arguments, as well as the state of all external variables surrounding each function declaration, which can cause side effects. These side effects increase the cognitive load of the state and make keeping track of the code difficult. RxJS offers a solution for dealing with the problem's side effects.

  • The business logic is tightly coupled within the nested callback structure, which adds complexity to the code. The more nested your code, the more difficult it will be to read and understand. RxJs is an excellent tool for developing reusable and modular components for loosely coupled business logic that can be maintained and unit tested independently.

  • A good responsive design always limits a user's interaction with any UI component so that the system is not overloaded unnecessarily. A manual solution is extremely difficult to implement correctly and involves functions that access data outside their local scope, compromising the overall stability of your programme. RxJS explains how to eliminate unnecessary overload by using throttling and debouncing.

Who uses RxJS ?


Today, almost every software company uses Reactive Programming to improve the performance of their applications. List of a few companies that use Reactive Programming, according to the ReactiveX website :

Prerequisites


Before beginning to learn and use RxJS, it is necessary to have the following knowledge:

  • Basic knowledge of programming in JavaScript or TypeScript
  • JavaScript Document object model, Functions, Events and Error Handling
  • Asynchronous JavaScript patterns (callbacks , promises etc.)
  • A clear understanding of Reactive programming and functional programming concepts.

Installation


current version 7.4.0

ES6 via npm

npm install rxjs

To check the vesion of installation :

first , install the 'version-check' library from npm using

npm install -g version-check

and then call

version-check rxjs

To import only what you need:

import { map } from 'rxjs/operators';

of(1, 2, 3).pipe(map(x => x + '!!!')); // etc

To import the entire core set of functionality:

import * as rxjs from 'rxjs';

rxjs.of(1, 2, 3);```

To use with a globally imported bundle:
```const { of } = rxjs;
const { map } = rxjs.operators;

of(1, 2, 3).pipe(map(x => x + '!!!')); // etc

All Module Types (CJS/ES6/AMD/TypeScript) via npm

To install this library via npm version 3, use the following command:

npm install @reactivex/rxjs

CDN

For CDN, you can use unpkg:

https://unpkg.com/rxjs@^7/dist/bundles/rxjs.umd.min.js

you can also download specific versions by just replacing version with the current version on the link below:

For RxJS 5.0.0-beta.1 through beta.11: https://unpkg.com/@reactivex/rxjs@version/dist/global/Rx.umd.js

For RxJS 5.0.0-beta.12 and higher: https://unpkg.com/@reactivex/rxjs@version/dist/global/Rx.js

For RxJS 6.0.0 and higher: https://unpkg.com/@reactivex/rxjs@version/dist/global/rxjs.umd.js

Advantages of RxJS


  1. RxJS is a functional and powerful tool that can be integrated into a variety of frameworks. It improves the appeal and approachability of reactive programming. It is rapidly expanding and evolving. The given link demonstrate its enormous popularity.

  2. RxJS is adaptable which can be used alongside other Javascript libraries and frameworks such as Angular, ReactJS, Vue.js, Nodejs, and others. It is supported by JavaScript as well as TypeScript.

  3. When it comes to handling async tasks, RxJS is an incredible and extensive library. RxJS employs observables in its reactive programming, which handles asynchronous data calls, callbacks, and event-driven programmes.

  4. RxJS has a graceful API that makes it simple to describe a complex stream of data in a concise and precise manner. RxJS includes a comprehensive set of standard entities such as Subjects, Observables, and operators that do all of the heavy lifting and make it possible. Using this method hides the complexity of the process from the developer, allowing him to concentrate on the logic of the product. Because of this high-quality API, a developer can significantly simplify the workflow with asynchronous data flows, freeing up time and effort for other tasks.

  5. RxJS comes with a comprehensive set of standard operators, but it may be necessary to eject repeating algorithms into new RxJS operators at times. RxJS's extensibility can help you do that.

  6. Another important advantage of RxJS is that it is well-maintained. Its constant updates on GitHub make it a good and dependable codebase. It provides constant and continuous updates to optimise RxJS's overall performance, making it even more impactful, dependable, and convenient.

Disadvantages of RxJS


  1. RxJS necessitates data immutability.To begin, we recognise that the need for data immutability in RxJS is not strictly a requirement, but rather a concept derived from functional programming, and the reactive paradigm works best and most optimally when combined with functional programming.

  2. RxJS's sole dependency is tslib, which provides Typescript support. Typescript has some advantages, such as strong typing, autocomplete, and so on, but it also has some incorrect use of access modifiers (private/public), which makes internal methods accessible from the outside.

  3. RxJS is mostly centred on using observables. As you begin to use observables, you may find that your entire code is wrapped up in the observables.

  4. Debugging code with observables is a little more difficult in RxJS. Because of some specific reactive programming features, a developer must be knowledgeable about supplementary methods and techniques in order to test RxJS code.

A simple example of RxJS


Consider how an event listener is used to handle a simple dom click event. Also, see how the same thing can be done with RxJS (reactive extension).

Vanilla JS code :

//Using JavaScript
document.addEventListener('click', () => console.log('Clicked from event Listener!'));

The same code in RxJS :

import { fromEvent } from 'rxjs';

const domObservable$ = fromEvent(document, 'click');
domObservable$.subscribe(() => console.log("Clicked from RxJS example!")));

EXPLANATION :

Normally, you would only assign an event listener to the dom element, as shown above. However, in the case of RxJS, you must first create an Observable and then subscribe to it.

The same code can be deconstructed in RxJS as shown below.

import { fromEvent } from 'rxjs';

fromEvent(document, 'click').subscribe(() => console.log('Clicked using Rxjs example!'));

Resources to learn RxJS