RxJS Higher Order Mapping
Learn how higher order mapping operators create and manage inner Observable streams using switchMap(), mergeMap(), concatMap() and exhaustMap().
What is Higher Order Mapping?
A higher order Observable is an Observable whose emitted values are themselves Observables.
Higher order mapping operators take a value from an outer Observable, use that value to create or select an inner Observable, and then control how those inner Observables are subscribed to.
Common operators are switchMap(), mergeMap(), concatMap() and exhaustMap().
Higher Order Mapping Flow
Why Use Higher Order Mapping?
Async Operations
Connect one Observable to another asynchronous operation.
Search
Handle changing search terms and API requests.
API Calls
Start an inner API Observable for each source value.
Concurrency Control
Control whether inner operations run, queue, merge or switch.
map() vs Higher Order Mapping
The normal map() operator transforms one value into another value.
Higher order mapping operators transform an outer value into an Observable and then control the resulting inner streams.
const result$ = source$.pipe(
map(value => value * 2)
);
const result$ = source$.pipe(
switchMap(value =>
getData(value)
)
);
Outer and Inner Observables
1. switchMap()
switchMap() maps each outer value to an inner Observable and switches to the newest inner Observable.
When a new outer value arrives, the previous inner subscription is cancelled.
const search$ = of(
'Java',
'.NET',
'Python'
);
const result$ = search$.pipe(
switchMap(course =>
of(course + ' results')
)
);
result$.subscribe({
next: result => {
console.log(result);
}
});
switchMap() Use Case
switchMap() is especially useful when only the latest request is relevant.
A common example is a search box where the user enters a new search term before the previous request has finished.
searchControl.valueChanges.pipe(
debounceTime(300),
switchMap(term =>
this.courseService.search(term)
)
).subscribe({
next: courses => {
this.courses = courses;
},
error: error => {
console.error(error);
}
});
Search Flow
User types: Java
User changes search: Java Full Stack
Latest search becomes the active request.
2. mergeMap()
mergeMap() maps each outer value to an inner Observable and subscribes to the inner Observables concurrently.
Multiple inner operations can therefore remain active at the same time.
const courseIds$ = of(
101,
102,
103
);
const result$ = courseIds$.pipe(
mergeMap(id =>
this.courseService
.getCourse(id)
)
);
result$.subscribe({
next: course => {
console.log(course);
}
});
mergeMap() Flow
3. concatMap()
concatMap() maps each outer value to an inner Observable and subscribes to those inner Observables sequentially.
The next inner Observable starts only after the previous inner Observable completes.
const topics$ = of(
'Introduction',
'Components',
'Services'
);
const result$ = topics$.pipe(
concatMap(topic =>
this.lessonService
.saveProgress(topic)
)
);
result$.subscribe({
next: response => {
console.log(response);
}
});
concatMap() Flow
4. exhaustMap()
exhaustMap() maps an outer value to an inner Observable and ignores new outer values while the current inner Observable is still active.
It is useful when only one operation should be processed at a time and additional triggers should be ignored until the current operation completes.
submitButtonClicks$.pipe(
exhaustMap(() =>
this.enquiryService
.submitEnquiry()
)
).subscribe({
next: response => {
console.log(response);
}
});
exhaustMap() Flow
Higher Order Mapping Operators Comparison
| Operator | New Inner Observable | Previous Inner | Main Behavior |
|---|---|---|---|
switchMap()
|
Starts latest | Previous is cancelled | Switch to latest |
mergeMap()
|
Starts immediately | Previous continues | Run concurrently |
concatMap()
|
Waits for turn | Previous continues | Run sequentially |
exhaustMap()
|
Ignored while active | Continues | Ignore new triggers during active work |
Which Operator Should You Choose?
switchMap()
Use when only the latest inner operation matters.
mergeMap()
Use when multiple inner operations may run concurrently.
concatMap()
Use when inner operations must be processed in order.
exhaustMap()
Use when new triggers should be ignored during active work.
CIIT Training Institute Example
Suppose a CIIT Training Institute website has a course search box. Every time the user enters a search term, the application needs to request matching courses from an API.
Since only the latest search is important, a switchMap() pipeline is suitable for this type of workflow.
searchControl.valueChanges.pipe(
debounceTime(300),
filter(term =>
term.length > 2
),
switchMap(term =>
this.courseService
.searchCourses(term)
)
).subscribe({
next: courses => {
this.courses = courses;
},
error: error => {
console.error(error);
}
});
CIIT Training Institute Course Search
Search: Angular
Search: Angular Full Stack
Latest search request is processed.
Sequential Save Example with concatMap()
Suppose several course-progress updates must be sent to the server in the same order in which they are generated.
concatMap() can be used to queue the inner operations and process them sequentially.
const progress$ = of(
'Components',
'Services',
'Routing'
);
progress$.pipe(
concatMap(topic =>
this.progressService
.save(topic)
)
).subscribe({
next: response => {
console.log(response);
}
});
Concurrent Operations with mergeMap()
When individual operations do not need to wait for each other, mergeMap() can allow multiple inner Observables to be active concurrently.
The order in which responses arrive should therefore not be assumed to be the same as the source order.
const ids$ = of(
101,
102,
103
);
ids$.pipe(
mergeMap(id =>
this.courseService
.getCourse(id)
)
).subscribe({
next: course => {
console.log(course);
}
});
Single Active Action with exhaustMap()
Consider a submit button that may be clicked several times while the current request is still running.
exhaustMap() can keep the first active request and ignore additional triggers until it completes.
submitClicks$.pipe(
exhaustMap(() =>
this.authService
.login()
)
).subscribe({
next: response => {
console.log(
'Login successful'
);
},
error: error => {
console.error(error);
}
});
Common Real-World Scenarios
| Scenario | Suggested Operator | Reason |
|---|---|---|
| Search as user types |
switchMap()
|
Latest search is more relevant |
| Independent requests |
mergeMap()
|
Operations can run concurrently |
| Ordered save operations |
concatMap()
|
Operations should execute sequentially |
| Submit button |
exhaustMap()
|
Ignore new triggers while active |
Important Points
The mapping function can return an Observable for each outer value.
Different operators decide whether inner streams are cancelled, merged, queued or ignored.
New source values switch the active inner subscription.
Select the operator according to whether work should run concurrently, sequentially, or only for the latest trigger.
Higher Order Mapping Best Practices
- Choose switchMap(), mergeMap(), concatMap() or exhaustMap() based on the required concurrency behavior.
- Do not use switchMap() automatically; make sure cancelling the previous inner operation is acceptable.
- Use concatMap() when ordering between inner operations matters.
- Use mergeMap() when concurrent inner operations are acceptable.
- Use exhaustMap() when repeated triggers should be ignored while one operation is active.
- Handle errors appropriately inside or around the Observable pipeline according to the required behavior.
Summary
Higher order mapping is used when an Observable value needs to produce or select another Observable.
switchMap() switches to the latest inner Observable, mergeMap() allows concurrent inner operations, concatMap() processes inner Observables sequentially, and exhaustMap() ignores new triggers while an inner Observable is active.
In the next topic, we will learn about Subjects.