Skip to main content

Angular - Difference between RxJS map, pluck, switchMap, mergeMap and exhaustMap

RxJS is a powerful library that provides a range of operators to work with asynchronous data streams. One of the most commonly used operators in RxJS is the map operator. The map operator allows you to transform the data emitted by an observable, and there are several different types of maps you can use. In this article, we will discuss the different types of RxJS maps and how they can be used in Angular.
  1. map()

The map() operator is the most commonly used operator in RxJS. It allows you to transform the data emitted by an observable by applying a function to each item emitted. For example, if you have an observable that emits a stream of numbers, you can use the map() operator to transform those numbers into strings:

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

const numbers$ = from([1, 2, 3, 4, 5]);

numbers$
  .pipe(
    map(num => `Number: ${num}`)
  )
  .subscribe(console.log);

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

In this example, the map() operator transforms the stream of numbers emitted by the observable into a stream of strings, by appending the string 'Number: ' to each number.

  1. pluck()

The pluck() operator allows you to extract a specific property from each object emitted by an observable. For example, if you have an observable that emits a stream of objects with 'name' properties, you can use the pluck() operator to extract only the 'name' properties:

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

const people$ = from([
  { name: 'John', age: 30 },
  { name: 'Mary', age: 25 },
  { name: 'Mike', age: 40 },
]);

people$
  .pipe(
    pluck('name')
  )
  .subscribe(console.log);

 

Output:

John
Mary
Mike

 

In this example, the pluck() operator extracts only the 'name' property from each object emitted by the observable, resulting in a stream of strings with the names.

  1. switchMap()

The switchMap() operator allows you to switch to a new observable whenever a new item is emitted by the source observable. For example, if you have an observable that emits a stream of user IDs, you can use the switchMap() operator to switch to a new observable that fetches the user data for each ID:

import { fromEvent } from 'rxjs';
import { switchMap } from 'rxjs/operators';

const button = document.querySelector('button');

const buttonClick$ = fromEvent(button, 'click');

buttonClick$
  .pipe(
    switchMap(() => fetch('https://jsonplaceholder.typicode.com/users'))
  )
  .subscribe(console.log);

In this example, the switchMap() operator switches to a new observable that fetches the user data for each button click. The result is a stream of user data objects emitted by the new observable.

  1. mergeMap()

The mergeMap() operator is similar to the switchMap() operator, but it merges the emissions of the inner observables instead of cancelling them out. For example, if you have an observable that emits a stream of user IDs, you can use the mergeMap() operator to merge the emissions of the observables that fetch user data for each ID:

import { fromEvent } from 'rxjs';
import { mergeMap } from 'rxjs/operators';

const button = document.querySelector('button');

const buttonClick$ = fromEvent(button, 'click');

buttonClick$
  .pipe(
    mergeMap(() => fetch('https://jsonplaceholder.typicode.com/users'))
  )
  .subscribe(console.log);

 

In this example, the mergeMap() operator merges the emissions of the observables that fetch user data for each button click, resulting in a stream of user data objects.

  1. exhaustMap()

The exhaustMap() operator allows you to ignore new emissions from the source observable until the current inner observable completes. For example, if you have an observable that emits a stream of user IDs, you can use the exhaustMap() operator to ignore new button clicks until the inner observable that fetches user data for the current ID completes:

import { fromEvent } from 'rxjs';
import { exhaustMap } from 'rxjs/operators';

const button = document.querySelector('button');

const buttonClick$ = fromEvent(button, 'click');

buttonClick$
  .pipe(
    exhaustMap(() => fetch('https://jsonplaceholder.typicode.com/users'))
  )
  .subscribe(console.log);

In this example, the exhaustMap() operator ignores new button clicks until the inner observable that fetches user data for the current click completes. Once it completes, the next button click will trigger a new inner observable.

Conclusion

The map() operator is just one of the many powerful operators available in RxJS. By understanding the different types of RxJS maps, you can use them to transform, filter, and merge data streams in a variety of ways. Whether you're working with Angular or any other JavaScript framework, RxJS maps can help you handle asynchronous data in a more efficient and readable way.

 

Comments

Popular posts from this blog

(Spanish) 8 Formas diferentes de ganar ingresos pasivos

Los ingresos pasivos se refieren al dinero ganado sin participación o esfuerzo activo. En lugar de intercambiar tiempo por dinero, los ingresos pasivos te permiten ganar dinero mientras duermes o te enfocas en otras actividades. A continuación, se presentan algunas formas diferentes de ganar ingresos pasivos: Propiedades de alquiler: Las propiedades de alquiler pueden ser una excelente fuente de ingresos pasivos. Una vez que compras una propiedad, puedes alquilarla y recibir pagos mensuales de alquiler. Con la administración adecuada de la propiedad, esto puede ser una fuente de ingresos sin tener que hacer mucho esfuerzo. Acciones de dividendos: Las acciones de dividendos son acciones que pagan dividendos de forma regular. Al invertir en acciones de dividendos, puedes recibir pagos regulares sin tener que vender tus acciones. Algunas compañías tienen una larga historia de pago de dividendos, y estas pueden ser fuentes confiables de ingresos pasivos. Préstamos entre particulares: Lo...

Rogan, Musk and Snoop

Joe: Hey guys, welcome to the show! Today we have Elon Musk and Snoop Dog joining us today. What's up? Elon: Not much, Joe. Just busy launching rockets and trying to colonize Mars. Snoop: And I'm just chillin', smokin' some weed, you know. Joe Rogan: So, Elon, you're known for pushing the limits of technology and innovation. What's the next big thing we can expect from you? Elon Musk: Well, Joe, we're working on a new project that will revolutionize the way we travel. We're creating a system of underground tunnels that will allow people to travel across cities at high speed. Joe Rogan: Oh, that's cool! But what if people get bored in the tunnels? Shouldn't you add some kind of entertainment? Snoop: Yeah, like strippers and pole dancing! Elon Musk: Well, that's an interesting idea, Snoop. But I think we'll stick to something a bit more practical. Joe Rogan: And what about colonizing Mars? What's the plan? Elon Musk: Well, Joe, it...

Andrew Tate has a talk with Moist Cr1TiKaL

Moist: Hey guys, welcome back. Today, I have a special guest with me - the one and only Andrew Tate. Now, I know what you're thinking. Why? And also, isn't he in prison? We will get to that later. Anyway, what's going on, Tate? Andrew Tate: Hey, Moist, what's with your name? Sounds like you're a wet tissue or something. Moist: Well, Andrew, I could ask you the same thing. What's with your name? Sounds like a Victorian chimney sweep. Andrew Tate: My name is unique and distinguished. Moist: Unique, sure. But distinguished? I'm not so sure about that. It's more like you got it from a random name generator. Andrew Tate: That's not true. I come from a long line of Tates. Moist: And I come from a long line of moist things, like cake and towelettes. Andrew Tate: Very funny. You know, I don't understand why people find your videos so entertaining. Moist: Well, I don't understand why people find your tweets so enlightening. Andrew Tate: Hey now. My ...