这个 RxJS 示例中的 switch 语句是做什么的?

What does the switch statement in this RxJS example do?

我不明白RxJS example中以下文档的含义。有人可以回答吗?

The outcome is that switched is essentially a timer that restarts on every click. The interval Observables from older clicks do not merge with the current interval Observable.

代码如下:

var clicks = Rx.Observable.fromEvent(document, 'click');
// Each click event is mapped to an Observable that ticks every second
var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000));
var switched = higherOrder.switch();
// The outcome is that `switched` is essentially a timer that restarts
// on every click. The interval Observables from older clicks do not merge
// with the current interval Observable.
switched.subscribe(x => console.log(x));

最容易理解的开关模型是 autocomplete

在典型的自动完成场景中,您将从用户那里获取输入,并调用一个 return 承诺的服务。然后您通过 .then() 附加到承诺以更新您的 UI.

function onChange(text: string) {
    this.request(url).then((data) => this.updateListBox(data))
}

如果用户多次输入文本,您将每次调用 onChange。无法保证此时响应的顺序。您呼叫的端点很可能 return 您的响应乱序。 132。因此用户将看到他们发出的第二个请求,而不是他们发出的最后一个请求。

现在 switch 做了什么,给定一个输入 observable,它只主动监听最后一个发送给它的 observable。例如...

this.onChange
   .map(text => Observable.fromPromise(this.request(text))
   .switch()
   .subscribe((data) => this.updateListBox(data));

每次通过 onChange 传入一个值时,我们仍会照常发出请求。一旦第二个值从 onChange 发出,我们就从第一个可观察对象(请求 1)unsubscribe 发出。并订阅第二个可观察对象(请求 2)。

因此,一旦您更新 UI,您只会更新您关心的最新数据集。