rxjs里switchMap operators的用法

时间:2022-07-28
本文章向大家介绍rxjs里switchMap operators的用法,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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

例子:

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

输出:

/*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是一个函数,接受一个number输入,返回一个Observable对象,包含3个number元素
    const fn = (x: number) => of(x, x ** 2, x ** 3);

    // OperatorFunction:尖括号里前一个number是输入类型
    // 第二个括号是输出类型
    const mapper: OperatorFunction<number, number> = switchMap(fn);

    // pipe需要接受的类型是OperatorFunction,经过operator传入一个
    // funcion进去组合而成
    const switched = origin.pipe(mapper);
    switched.subscribe(x => console.log('diablo: ' + x));

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);
    // 需要传一个Observable进去
    const mapper = switchMapTo(int);
    const switched = origin.pipe(mapper);
    switched.subscribe(x => console.log('diablo2: ' + x));

测试结果:origin里的value完全没有被考虑: