switchAll

switchAll()

很好的例子是搜索。当用户输入某些文本时,将请求异步发送到服务器,结果将作为observable返回。如果用户在返回结果之前更新搜索框中的文本,该怎么办?发送第二个请求,因此现在已经向服务器发送了两个搜索,但是,第一次搜索结果已经不再需要了。所以使用switchAll,它选择最近的流生成的值,而忽略先前的流。

import { fromEvent, interval } from "rxjs";
import { switchAll, map } from "rxjs/operators";

//立即取消以前的订阅, 而订阅新的数据流
const source = fromEvent(document, "click").pipe(map(() => interval(1000)));
source.pipe(switchAll()).subscribe(console.log);