DEV Community

Kafeel Ahmad (kaf shekh)
Kafeel Ahmad (kaf shekh)

Posted on

RxJs In Practice

RxJs is a library for reactive programming using Observables, which allows you to work with asynchronous data streams. Observables are sequences of values that can be emitted over time, and you can apply a variety of operators to these sequences to transform or manipulate the data.

Here are a few examples of how you can use RxJs in practice:

Filtering data: You can use RxJs to filter data based on certain criteria. For example, you could use the filter operator to only emit values from an Observable that meet a certain condition. Let's say you have an Observable of numbers, and you only want to emit values that are even:

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

const numbers$ = from([1, 2, 3, 4, 5, 6]);
const evenNumbers$ = numbers$.pipe(filter(n => n % 2 === 0));

evenNumbers$.subscribe(console.log); // Output: 2, 4, 6

Enter fullscreen mode Exit fullscreen mode

Transforming data: You can also use RxJs to transform data from one format to another. For example, you could use the map operator to convert a stream of numbers into a stream of strings. Let's say you have an Observable of numbers, and you want to emit a string that says whether each number is even or odd:

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

const numbers$ = from([1, 2, 3, 4, 5, 6]);
const evenOrOdd$ = numbers$.pipe(map(n => n % 2 === 0 ? `${n} is even` : `${n} is odd`));

evenOrOdd$.subscribe(console.log); // Output: "1 is odd", "2 is even", "3 is odd", "4 is even", "5 is odd", "6 is even"

Enter fullscreen mode Exit fullscreen mode

Combining data: You can also use RxJs to combine data from multiple sources into a single stream. For example, you could use the combineLatest operator to combine two Observables of numbers into a single Observable that emits the sum of the two numbers whenever either of them changes. Let's say you have two Observables of numbers, a$ and b$:

import { fromEvent, combineLatest } from 'rxjs';
import { map } from 'rxjs/operators';

const a$ = fromEvent(document.getElementById('input-a'), 'input').pipe(
  map(e => Number(e.target.value))
);
const b$ = fromEvent(document.getElementById('input-b'), 'input').pipe(
  map(e => Number(e.target.value))
);

const sum$ = combineLatest([a$, b$]).pipe(
  map(([a, b]) => a + b)
);

sum$.subscribe(console.log); // Output: the sum of input-a and input-b

Enter fullscreen mode Exit fullscreen mode

In this example, we're using the combineLatest operator to combine the latest values from both a$ and b$ into an array, and then using the map operator to add those values together and emit the result. Whenever either a$ or b$ emits a new value, the sum$ Observable will emit the new sum.

Thank You for reading 😊

Top comments (0)