DEV Community

Deborah Kurata
Deborah Kurata

Posted on

Higher-Order Mapping Operators

Higher-order mapping operators are used to map inner Observables. They include:

  • concatMap
  • mergeMap
  • switchMap

image

Each higher-order mapping operator:

  • Automatically subscribes to the inner Observable
  • Flattens the resulting Observable, returning Observable<T> instead of Observable<Observable<T>>
  • Automatically unsubscribe from the inner Observable

For example:

products$ = this.categorySelected$
  .pipe(
       switchMap(catId=>
            this.http.get<Product[]>(`${this.url}?cat=${catId}`))
  );

Enter fullscreen mode Exit fullscreen mode

In this code, every time the user selects a new category, this.categorySelected$ emits the id of the selected category. That id is piped through a higher-order mapping operator (switchMap in this case). The switchMap automatically subscribes to the inner Observable, flattens the result (emitting an array of type Product[] instead of Observable<Product[]>), and unsubscribes from the inner Observable.

Additional posts in this series look more closely at several higher-order mapping operators and when to use which.

Top comments (0)