在StackBlitz里创建一个rxjs项目,源代码如下:
import { Observable, of } from "rxjs";
import { map } from "rxjs/operators";
import { interval } from "rxjs";
import { switchMap } from "rxjs/operators";
const pollTasks = () => {
return interval(1000).pipe(
switchMap(counter => {
return of(counter + 100);
}),
map(res => res + res)
);
};
// 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(), 10000);
十秒之后自动关闭:
首先用rxjs interval创建一个Observable对象,每隔1秒钟产生一个递增的整数:
interval(1000)返回的Observable调用pipe进行下一步处理:switchMap.
注意该switchMap的类型,接受一个输入参数,project函数。该project函数的输入是:value: number, index: number, 必须返回Observable. 整个project的函数类型是OperatorFunction<number, number>.
下面这个例子更加能够说明问题:
import { Observable, of, OperatorFunction } from "rxjs";
import { map } from "rxjs/operators";
import { interval } from "rxjs";
import { switchMap } from "rxjs/operators";
const add1Fn = value => value + 1;
const add1OP: OperatorFunction<number, number> = map(add1Fn);
const pollTasks = () => {
return interval(1000).pipe(
switchMap(counter => {
return of(counter + 100);
}),
map(res => res + res),
add1OP
);
};
// 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);
将函数传入rxjs的operator,返回的是一个operatorFunction,将这个operatorFunction传入pipe,返回的是新的Observable.
更多Jerry的原创文章,尽在:“汪子熙”: