Higher-Order Mapping Operators
Deborah Kurata
Posted on August 19, 2021
Higher-order mapping operators are used to map inner Observables. They include:
- concatMap
- mergeMap
- switchMap
Each higher-order mapping operator:
- Automatically subscribes to the inner Observable
- Flattens the resulting Observable, returning
Observable<T>
instead ofObservable<Observable<T>>
- Automatically unsubscribe from the inner Observable
For example:
products$ = this.categorySelected$
.pipe(
switchMap(catId=>
this.http.get<Product[]>(`${this.url}?cat=${catId}`))
);
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.
đź’– đź’Ş đź™… đźš©
Deborah Kurata
Posted on August 19, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.