Angular mergeMap vs switchMap

Asked on May 12, 2019
Hi, What is difference between RxJS mergeMap and switchMap in Angular application?
Provide some examples.

Replied on May 12, 2019
mergeMap
RxJS
mergeMap
operator projects each source value to an Observable
and finally they are merged into output Observable
using RxJS mergeAll
operator.of('x', 'y', 'z').pipe(
mergeMap(el => of(1, 2).pipe(
delay(2000),
map(num => el+num)
)
)
).subscribe(res => console.log(res));
mergeMap(el => of(1, 2).pipe(
delay(2000),
map(num => el+num)
)
)
).subscribe(res => console.log(res));
The 'x', 'y', 'z' elements from the source
Observable
will be emitted to mergeMap
. The inner Observable
will emit 1, 2 number for every elements of source Observable
. We are delaying inner Observable
process by 2 seconds and hence before completing request for 'x' element, the 'y' and 'z' element will also enter into mergeMap
. So mergeMap
will wait for completion of inner Observable
for all the three elements and finally will merge them into one Observable
as output of mergeMap
.
We can understand merging of inner
Observable
into one as following.
of(x1) + of(x2) + of(y1) + of(y2) + of(z1) + of(z2) = of(x1, x2, y1, y2, z1, z2)
When we subscribe, we will get output x1, x2, y1, y2, z1, z2.
If inner
Observable
of mergeMap
, is responding for any emitted element from source Observable
before getting request for new element, then there is nothing to merge.
Reference:
switchMap
RxJS
switchMap
emits Observable
after applying the given function to each item emitted by source Observable
. The Observable
emitted by given function that is also called inner Observable
, is returned by switchMap
operator. switchMap
starts emitting items emitted by inner Observable
. When a new inner Observable
is emitted, the switchMap
stops emitting items from previous inner Observable
and starts emitting items from latest inner Observable
. It continues to do in the same way for all subsequent inner Observable
. switchMap
is a RxJS pipeable operator and it is used within pipe
function of Observable
from RxJS 6.In search operation, user may frequently change search keyword. So it is
important that we should get result only with latest search keyword.
For any keyword
switchMap
will emit items from inner Observable
and if before completion a new search keyword is hit, then switchMap
will stop emitting previous inner Observable
and start emitting the latest inner Observable
. Hence user always gets the result for latest search keyword. switchMap
is used as following. searchBook() {
this.bookId.valueChanges.pipe(
switchMap(id => {
console.log(id);
return this.bookService.getBook(id);
})
).subscribe(res => this.book = res);
}
this.bookId.valueChanges.pipe(
switchMap(id => {
console.log(id);
return this.bookService.getBook(id);
})
).subscribe(res => this.book = res);
}
Reference: