The maps of rxjs

Who am I?

  • Have been doing web dev for 3.5 years
  • RxJS enthusiast
  • Currently a Progress employee working on KendoUI for Angular

Four map operators

Aren't they the same?

The "same, same"

  • All have "map" in their name
  • All are higher order observables
someStream.pipe(
    /*merge || switch || concat || exhaust*/map((value) => otherStream(value))
)

The "different"

  • Perform their tasks in different way

The "still same"

  • Perform flattening + mapping

The scenario

Calling the backend in different ways

this.actions$.pipe(
  ofType<PostsActions.GetPostsById>(
    PostsActions.PostsActionTypes.GetById
  ),
  map(action => action.payload),
  switchMap((id: string)=> {
    return this.postsService.get(id).pipe(
      map((post: Post) => new PostsApiActions.GetSuccess(post)),
      catchError(err => of(new PostsApiActions.GetFailure(err)))
    );
  })
);

mergeMap

"Fire at will"

fromEvent(this.button.nativeElement, 'click').pipe(
  mergeMap(() => backend())
);

Performs all requests the moment they are initialized

Use cases

  • Adding items to shopping cart
  • Liking multiple things on social network
  • Anything that you want done in succession but don't care about the order of execution

switchMap

"All others are out"

fromEvent(this.button.nativeElement, 'click').pipe(
  switchMap(() => backend())
);

Perform the last request only, cancel all previous unfinished ones

Use cases

  • Most used for general scenarios
  • Autocomplete with API call

concatMap

"Wait for your turn"

fromEvent(this.button.nativeElement, 'click').pipe(
  concatMap(() => backend())
);

Perform next request only after the previous one is done

Use cases

  • Chat app(order of requests matter)
  • A game where order of keypresses is important

exhaustMap

"Do not disturb me!"

fromEvent(this.button.nativeElement, 'click').pipe(
  exhaustMap(() => backend())
);

Ignores all other requests until finished with the ongoing one

Use cases

  • Preventing user from restarting a request
  • Login screens
  • Helps decrease backend load

Recap

  • mergeMap - Map to observable, emit values
  • switchMap - Map to observable, complete previous inner observable, emit values
  • concatMap - Map values to inner observable, subscribe and emit in order
  • exhaustMap - Map to inner observable, ignore other values until that observable completes

Thank you

Made with Slides.com