rxjs里switchMap operators的用法

736 阅读1分钟

switchMap相关文章

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,亦即SwitchMap返回的OperatorFunction,其function的输出是一个新的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));

总结:OperatorFunction的类型很形象,由Operator接收一个function作为输入,组装而成

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完全没有被考虑:

要获取更多Jerry的原创文章,请关注公众号"汪子熙":