Reactive Programming with JavaScript and RxJS


Reactive programming is a programming paradigm that deals with asynchronous data streams. It is a way of writing code that is more responsive to change, and that can handle events and data streams in a more efficient way.

In reactive programming, data is represented as a stream of events. These events can be anything from user input to network requests to database updates. The program then subscribes to these events, and reacts to them as they happen.

This approach to programming has a number of advantages. First, it makes it easier to deal with asynchronous data. In traditional programming, asynchronous data can be difficult to handle, as it can be difficult to know when the data will be available. Reactive programming, on the other hand, handles asynchronous data in a more natural way, by treating it as a stream of events.

Second, reactive programming can help to improve the performance of your code. By subscribing to events, your code can be notified as soon as new data is available, so that it doesn't have to poll for data or wait for events to happen.

Finally, reactive programming can help to make your code more maintainable. By treating data as a stream of events, your code becomes more declarative, and it is easier to understand how the different parts of your code interact with each other.

RxJS

RxJS is a JavaScript library that provides a reactive programming API. It is a popular library, and it is used by a number of popular JavaScript frameworks, such as Angular and React.

RxJS provides a number of features that make it well-suited for reactive programming. These features include −

  • Observables  Observables are the basic building blocks of RxJS. They represent a stream of events, and they can be used to represent any type of data, including numbers, strings, objects, and arrays.

  • Operators  Operators are functions that can be used to transform, filter, and combine Observables. There are a large number of operators available in RxJS, which makes it possible to do a wide variety of things with Observables.

  • Schedulers  Schedulers are used to control the timing of Observables. They can be used to make Observables fire at a specific time, or to delay the emission of events.

Installing RxJS

To get started with RxJS, we need to install it. Open your terminal and run the following command −

npm install rxjs

Once the installation is complete, we can begin exploring the power of reactive programming with RxJS.

Creating Observables

Observables are at the core of RxJS. They represent a stream of data that can be observed by subscribers.

Let's start by creating a simple Observable that emits a sequence of numbers −

Example

import { Observable } from 'rxjs';

const numberObservable = new Observable((observer) => {
   let count = 0;

   const interval = setInterval(() => {
      observer.next(count);
      count++;

      if (count > 5) {
         clearInterval(interval);
         observer.complete();
      }
   }, 1000);
});

numberObservable.subscribe((number) => {
   console.log(number);
});

Explanation

In the code above, we create an Observable using the Observable class from RxJS. Inside the constructor function, we define the logic for emitting values. In this example, we use setInterval to emit a number every second. Once the count reaches 5, we stop the interval and call observer.complete() to signal the end of the stream.

To observe the values emitted by the Observable, we call the subscribe method and provide a callback function. In this case, the callback function simply logs the emitted number to the console.

Output

0 
1
2 
3 
4
5

Operators in RxJS

RxJS provides a wide range of operators that allow us to transform, filter, combine, and manipulate the data emitted by Observables. Let's take a look at a few common operators.

Map Operator

The map operator allows us to transform the values emitted by an Observable. For example, let's modify our previous example to double the emitted numbers −

Example

import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

const numberObservable = new Observable((observer) => {
   let count = 0;

   const interval = setInterval(() => {
      observer.next(count);
      count++;

      if (count > 5) {
         clearInterval(interval);
         observer.complete();
      }
   }, 1000);
});

numberObservable
   .pipe(map((number) => number * 2))
   .subscribe((number) => {
      console.log(number);
   });

Explanation

In this code, we use the pipe method to chain the map operator onto our Observable. The map operator takes a callback function that transforms each emitted number by doubling it. The resulting values are then passed to the subscriber's callback function.

Output

0
2
4
6
8 
10

Filter Operator

The filter operator allows us to selectively filter out values emitted by an Observable based on a condition. Let's add a filter to our previous example to only emit even numbers −

Example

import { Observable } from 'rxjs';
import { filter } from 'rxjs/operators';

const numberObservable = new Observable((observer) => {
   let count = 0;

   const interval = setInterval(() => {
      observer.next(count);
      count++;

      if (count > 5) {
         clearInterval(interval);
         observer.complete();
      }
   }, 1000);
});

numberObservable
   .pipe(filter((number) => number % 2 === 0))
   .subscribe((number) => {
      console.log(number);
   });

Explanation

In the provided code, we are creating an Observable called numberObservable that emits a sequence of numbers. The Observable emits numbers starting from 0 and increments by 1 every second using setInterval. After emitting the number 5, the interval is cleared, and the Observable signals completion using observer.complete().

Next, we apply the filter operator to the numberObservable using the pipe method. The filter operator takes a callback function that defines a condition. It filters out the values that do not satisfy the condition, allowing only even numbers to pass through.

Finally, we subscribe to the filtered Observable and log each emitted number to the console using the subscriber's callback function.

Output

0
2
4

Conclusion

In conclusion, Reactive Programming with JavaScript and RxJS offers a powerful and efficient way to handle asynchronous data streams and build responsive applications. By embracing the concept of Observables and leveraging the rich set of operators provided by RxJS, developers can easily manipulate, transform, and combine data streams in a declarative and elegant manner.

Through the examples discussed in this article, we have seen how to create Observables, apply operators like map and filter to transform and filter emitted values, and subscribe to Observables to receive and process the data. RxJS simplifies the management of complex asynchronous flows by providing a consistent and composable approach.

Updated on: 25-Jul-2023

402 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements