In previous article we have seen RxJS mergeMap, applying Observable in merge strategy to a series of HTTP operations to run things in parallel.  

Important Opertaor

Flatting Opertaot – Means to avoide subscirbing two times observable

Most use In search functinality

The main difference between switchMap and other flattening operators is the cancelling effect. On each emission the previous inner observable (the result of the function you supplied) is cancelled and the new observable is subscribed. You can remember this by the phrase switch to a new observable.

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..

This works perfectly for scenarios like typeaheads where you are no longer concerned with the response of the previous request when a new input arrives. This also is a safe option in situations where a long lived inner observable could cause memory leaks, for instance if you used mergeMap with an interval and forgot to properly dispose of inner subscriptions. Remember, switchMap maintains only one inner subscription at a time, this can be seen clearly in the first example.

Be careful though, you probably want to avoid switchMap in scenarios where every request needs to complete, think writes to a database. switchMap could cancel a request if the source emits quickly enough. In these scenarios mergeMap is the correct option.

const searchText$: Observable<string> = 
    fromEvent<any>(this.input.nativeElement, "keyup")
        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$
        switchMap(search => (){
            const params = new HttpParams().set("search", search);
            return this.http.get("/api/book/", {params});

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

Use Cases:


  Let's say you have an Observable that emits User IDs. You may want to fetch the full User object correlating to the ID, then do something with the full details. The switchMap operator would receive the ID from the Observable, then return an Observable containing the response from the request to fetch the User object. 

const userDetails$ = from(this.userService.getActiveUserID())
    .pipe(switchMap(id => this.userService.fetchUserForID(id)))
    .subscribe(user => console.log("Found user ", user));

  Here, we ask for the active user's ID. Then, we ask the userService to make an ajax request to our backend to fetch the User that correlates with the ID. We are assuming that the fetchUserForID call returns an Observable.


  It's worth noting that the switchMap operator will cancel any in-flight network requests if it receives a new value from the original (commonly known as the source) Observable stream, making it a great candidate for typeahead search implementations!  

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Leave a Comment