bluehost-banner
What is SwitchMap operator - RXJS

What is SwitchMap operator - RXJS

In the previous article, we have seen the mergeMap operator, now we will see another important operator of RXJS which SwtichMap operator.

The SwitchMap operator is the most Important Operator of RXJS.

Flatting Opertaot – Means to avoid subscribing two times observable.

SwitchMap operator is mostly used In search functionality

What is SwitchMap - RXJS Operator?

The main difference between switchMap and other flattening operators is the canceling effect. On each emission, the previous inner observable (the result of the function you supplied) is canceled 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")
    .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 into 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

Also read,

SwitchMap Use Cases:

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

2)  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!  

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

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.

You might also like

Leave a Comment