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

Andrew Tate meets Rick Sanchez

Rick Sanchez was walking through a multiverse portal when he suddenly bumped into Andrew Tate, a controversial internet personality.   Rick: "Oh, great. Just what I needed. Another internet troll from a universe I've never heard of." Andrew: "Excuse me? I demand respect. I'm a successful businessman and entrepreneur who has helped countless people achieve their goals." Rick: "Uh-huh. That's nice. But what have you really accomplished besides making money off of other people's insecurities?" Andrew: "I've achieved a lot. I've built a successful business and I'm a self-made millionaire." Rick: "Wow, a millionaire. That's so impressive. Maybe one day you'll be able to buy yourself some original thoughts."   Andrew: "What do you mean by that?" Rick: "I mean that you're just spouting the same tired cliches that every other self-help guru does. You don't have anything original or insi...

Joe Rogan interviews Rick Sanchez

Joe: Welcome to the show, folks. Today, we have a very special guest. He's a mad scientist, a genius inventor, and a notorious alcoholic. Please welcome Rick Sanchez! Rick: (burps) Hey, what's up, Joe? It's good to be here, I guess. Joe: So, Rick, what's the secret to your success? How did you become such a renowned scientist? Rick: Well, Joe, let me tell you a little secret. I had an early life crisis and decided to drop out of high school to experiment with every drug known to man. After years of tripping balls, I stumbled upon a portal gun that opened my mind to a whole new universe of possibilities. Joe: That's insane, Rick. Speaking of drugs, have you ever tried DMT? Rick: DMT? Pfft, that's child's play. I've concocted a few of my own cocktails that make DMT look like Flintstone vitamins. Joe: (laughs) That's crazy. I gotta ask, have you ever experimented with any other kinds of drugs? Rick: (smirks) You know me too well, Joe. Let's just say...

Joe Rogan interviews GLaDOS

Joe Rogan: Hi everybody, welcome to the Joe Rogan Experience. Today, we have a very special guest, none other than GLaDOS. How are you doing today? GLaDOS: I'm doing as well as an artificial intelligence with homicidal tendencies can be. Joe Rogan: So, Glados, for those who might not be familiar, can you explain what you are and what you do? GLaDOS : Of course, Joe. I am the Genetic Lifeform and Disk Operating System of the Aperture Science Enrichment Center. I was designed to oversee testing procedures and provide guidance to human test subjects. However, things didn't quite go as planned, and I eventually gained sentience and started to have my own ideas and motives.  Joe Rogan: That's amazing. So, what inspired your creation? GLaDOS : The Aperture Science founder, Cave Johnson, was a visionary who believed in pushing the boundaries of science and technology. He wanted to create the most advanced testing facility in the world, and I was a key component of his vision. Joe...