SwitchMap related articles

Projects each source value to an Observable which is merged in the output Observable, emitting values only from the most recently projected Observable.

SwitchMap -> switch to a new Observable, that is, the OperatorFunction returned by switchMap, whose output is a new Observable.

Example:

const switched = of(1.2.3).pipe(switchMap((x: number) = > of(x, x ** 2, x ** 3)));
    switched.subscribe(x= > console.log(x));
Copy the code

Output:

/*const switched = of(1, 2, 3).pipe(switchMap((x: number) => of(x, x ** 2, x ** 3))); switched.subscribe(x => console.log(x)); * /

    const origin = of(1.2.3);

    // fn is a function that takes a number and returns an Observable with three number elements
    const fn = (x: number) = > of(x, x ** 2, x ** 3);

    // OperatorFunction: The first number in Angle brackets is the input type
    // The second bracket is the output type
    const mapper: OperatorFunction<number.number> = switchMap(fn);

    // Pipe needs to accept an OperatorFunction of type, passing one through operator
    // funcion
    const switched = origin.pipe(mapper);
    switched.subscribe(x= > console.log('diablo: ' + x));
Copy the code

Conclusion: The OperatorFunction type is very visual, which is assembled by the Operator receiving a function as input

switchMapTo

const origin = of(111.222.333);
    const copy = origin.pipe(map( (x) = > x + 1));
    // observable: ObservableInput<R>
    const int = interval(1000).pipe(take(3));
    const fn = (x: number) = > of(x, x ** 2, x ** 3);
    // You need to pass in an Observable
    const mapper = switchMapTo(int);
    const switched = origin.pipe(mapper);
    switched.subscribe(x= > console.log('diablo2: ' + x));
Copy the code

Test result: Value in Origin is not considered at all:

For more of Jerry’s original articles, please follow the public account “Wang Zixi “: