Rxjs Heaven (Part3: Higher-order operators )

Introduction 🚩 :

  • Part2: Multi-Casting Operators with Rxjs (Published )
  • Part3: Higher-order operators with Rxjs ( Current blog )
  • Part4: Custom operators with Rxjs ( coming soon ⏳)

Higher-order operators:

There are a lot of important operators in reactive programming, one of them are higher-order mapping operators: switchMap, mergeMap, concatMap, and exhaustMap which they are the most used operators with Rxjs ,

Definition β˜‘οΈ :

A higher-order Observable is an Observable that emits other Observables

Advantage βœ”οΈ :

They are used to avoid the nested subscription anti-pattern

(A) concatMap Operator πŸ“–:

concatMap is a combination of two operators concat and map that can be used to run Observables in sequence.

  • ajax: It creates an observable for an Ajax request
  • concatMap: will be used to run the observable list in sequence and wait for all these subscriptions to be finished to complete

(B) The switchMap Operator πŸ“–:

SwitchMap is an operator that can be used for Observable Switching :

source: https://yakovfain.com/2017/09/19/rxjs-essentials-part-6-the-switchmap-operator/

Usage :

With Route Parameters

  • debounceTime(400): this operator used to delay values emitted by the source Observable terms
  • distinctUntilChanged(): this operator used to emit value only when the new value is different from the current one
  • switchMap((term):
  • this.http.get(this.baseUrl + this.queryUrl + term): this code to mak an API call with httpClient provided by Angular

(C) mergeMap Operator πŸ“–:

MergeMap is an operator that can be used to run sequentially observables

  • getCommentsWithPost: to get list of comments related to the post in params
  • tap((item) => console.log(β€˜yes !’, item)) : an operator used for side-effect to log each mapped item
  • mergeMap(this.getCommentsWithPost) : we will use the mergeMap operator to ..

References πŸ““ πŸ“• :

Conclusion β€οΈπŸ‘:

For Conclusion, we explored the Rxjs high order operators with some cod-examples and use cases



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store