Website: https://www.learnrxjs.io/lear…

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.

The primary difference between switchMap and the other flattening operators is the cancellation effect. On each launch, the previous internal Observable (the result of the function you provided) is canceled and subscribed to a new Observable. You can remember this by using the phrase switch to a new Observable.

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.

This works well for scenarios like pre-input, where you no longer care about the response to the previous request when new input arrives. It is also a safe choice in cases where a long-lived internal Observable can cause memory leaks.

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.

Be careful, however, that you may want to avoid switchMap in situations where every request needs to be completed, such as writing to a database scenario. SwitchMap can cancel the request if the source is issuing fast enough. In these cases, Mergemap is the right choice.

Look at this example:

import { interval, fromEvent } from 'rxjs';
import { switchMap } from 'rxjs/operators';

fromEvent(document, 'click')
.pipe(
  // restart counter on every click
  switchMap(() => interval(1000))
)
.subscribe(console.log);

Each time you click on the screen, the MouseEvent from FromEvent Issue, passed inside the SwitchMap, will restart a new timer with a 1-second interval and cancel the previous timer. It is printed as follows:

Here is another example of implementing a timer:

import { Component, OnInit } from '@angular/core'; import { interval, fromEvent, merge, empty } from 'rxjs'; import { switchMap, scan, takeWhile, startWith, mapTo } from 'rxjs/operators'; const COUNTDOWN_SECONDS = 1000; @Component({ selector: 'switchMap-study', templateUrl: './switchMap.component.html' }) export class SwitchMapComponent implements OnInit { ngOnInit(): void { // elem refs const remainingLabel = document.getElementById('remaining'); const pauseButton = document.getElementById('pause'); const resumeButton = document.getElementById('resume'); // streams const interval$ = interval(1000).pipe(mapTo(-1)); const pause$ = fromEvent(pauseButton, 'click').pipe(mapTo(false)); const resume$ = fromEvent(resumeButton, 'click').pipe(mapTo(true)); const timer$ = merge(pause$, resume$).pipe( startWith(true), switchMap(val => (val ? interval$ : empty())), scan((acc, curr) => (curr ? curr + acc : acc), COUNTDOWN_SECONDS), takeWhile(v => v >= 0)).subscribe((val: any) => (remainingLabel.innerHTML = val)); }}
<h1>Switch Map Study</h1>

<a href="https://www.learnrxjs.io/learn-rxjs/operators/transformation/switchmap">Document</a>

<h4>
    Time remaining: <span id="remaining"></span>
    </h4>
    <button id="pause">
    Pause Timer
    </button>
    <button id="resume">
    Resume Timer
</button>

Start with true so the switchMap continues. SwitchMap project (val, Boolean) returns a new Observable, internal$.

Note the use of empty(), which returns an Observable of type Never.

Creates an Observable that emits no items to the Observer and immediately emits a complete notification.

Just emits ‘complete’, and nothing else.

This static operator is useful for creating a simple Observable that only emits the complete notification. It can be used for composing with other Observables, such as in a mergeMap.

Single pacing is piloted after pause:

The unsubscribe method in line 41 demonstrates the switchMap feature that automatically cancels the previous internal Observable:

Cancel and subscribe to a new Observable:

If empty is returned, subsequent scans will not be performed:

We can modify the switchMap input parameter, projection:

The type of this projection is an arrow function, the input parameter is a Boolean, and the output is a new Observable.

More of Jerry’s original articles can be found on “Wang Zixi “: