通过rxjs的一个例子, 来学习SwitchMap的使用方法

219 阅读1分钟

switchMap相关文章

源代码:

import { Observable, of, OperatorFunction } from "rxjs";
import { map } from "rxjs/operators";
import { interval } from "rxjs";
import { switchMap } from "rxjs/operators";

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

switchMap将source value映射成一个新的Observable,这个Observable被output Observable自动merge.
只会从最新的被projected过后的Observable里emit数据
给consumer
*/

const add100 = (counter: number) => {
  return of(counter + 100);
};

const addFunctionOperator: OperatorFunction<number, number> = switchMap(add100);

const pollTasks = () => {
  return interval(1000).pipe(addFunctionOperator);
};

// caller can do subscription and store it as a handle:
let tasksSubscription = pollTasks().subscribe(data =>
  console.log("timestamp: " + new Date() + ": " + data)
);
// turn it off at a later time

setTimeout(() => tasksSubscription.unsubscribe(), 3000);

在这里插入图片描述

由此可见,switchMap操作符接收一个映射函数,该函数的输入同map操作符一样,都是number,而map的输出类型也是number,而switchMap的输出,是Observable.

switchMap传入一个函数,输出一个OperatorFunction, 这称为函数的operator化。

OperatorFunction才是最后传入Observable.pipe调用里的参数。