RxJS switchMap (2024)
RxJS Tutorial - Table of Contents
Overview
In previous article we have seen RxJS mergeMap, applying Observable in merge strategy to a series of HTTP operations to run things in parallel.
Let's talk now about another Combination Strategy Observable: switching. In the sense we won't wait for an Observable to end, the concept of shifting is closest to merge rather than concatenation.
In switching, unlike merging, we'll unsubscribe the previous Observable before subscribing to the new Observable if the new Observable begins to emit the values..
RxJS switchMap Operator Marble Diagram
Take the switch strategy and use it to higher order mapping. We have a simple input stream, which transmits values 1, 3 and 5.
Then each value will be mapped to an Observable and an Observable in higher order. This higher-order Observable emits values which are themselves Observables.
If we switch from the emitted inner Observables to the switchMap Operator. Let's look at the operator's marble diagram: >
This is how the operator switchMap works:
- source observable emits values 1, 3 and 5, these values are then turned into Observables by applying a mapping function
- the mapped inner Observables get subscribed to by switchMap
- The value is immediately reflected in the output when the inner Observable emits a value.
- If a new value such as 5 is emitted before the previous Observable is completed, Then the previous Observable (30-30-30) will be unsubscribed first and its remaining values will no longer be reflected in the resulting Observable.
- That is why the inner Observable 30-30-30 is highlighted in red, as the last 30 was not emitted because the inner Observable 30-30-30 was unsubscribed.
RxJS switchMap Operator Example
Here is the sample code looks like if we now use the switchMap Operator:
const searchText$: Observable<string> =
fromEvent<any>(this.input.nativeElement, "keyup")
.pipe(
map(event => event.target.value), // map to form input component value
startWith(""), // avoid spaces
debounceTime(400), // delay request by 400 ms to avoid sending multiple request while user still typing
distinctUntilChanged() // prevent duplicate request on retype
);
const lessons$: Observable<Lesson[]> = searchText$
.pipe(
switchMap(search => (){
const params = new HttpParams().set("search", search);
return this.http.get("/api/book/", {params});
)
)
.subscribe();
Check Typeahead is a very common use case for switchMap. This origin, Observable (formevent), will emit values once user types in input text field
In this context, we want to turn each user input string to a backend request and subscribe to it and apply the switching strategy between two consecutive search requests, so that the previous search can be terminated if a new request is triggered with the help of switchMap operator
Next we will see RxJS Interview Questions