RxJS 动态分配按钮的多个订阅



假设我有一个角度 2 分量,如下所示:

import { Component, AfterViewInit, ViewChildren, QueryList, ElementRef } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import {ApiService} from './my.service'
@Component({
selector: 'my-component',
template: `
<div class='button0' [ngClass]="{selected: selection === 0}" #button>Hello World</div>
<div class='button1'  [ngClass]="{selected: selection === 1}" #button>Hello World</div>
`,
styles: [`
.selected {
color: red;
}
`],
providers: [ApiService]
})
export class MyComponent implements AfterViewInit { 
selection = 0;
@ViewChildren('button') buttons: QueryList<ElementRef>;
buttonObservables:any[] = null;
constructor(private api: ApiService) {}
updateServer(index) {
api.requestsExample(index)
.then((result) => {
//update other divs and stuff
}
}

updateColor(index) {
this.selection = index;
}
ngAfterViewInit () {
this.buttonObservables = this.buttons.map((button) => Observable
.fromEvent<MouseEvent>(button.nativeElement, 'click'));
this.buttonObservables.map((observable) => {
observable.throttleTime(2000).subscribe((event:MouseEvent) => {
const element:Element = event.target as Element;
this.updateServer(element.classList[1].match(/d+/g));
})
});
this.buttonObservables.map((observable) => {
observable.subscribe((event:MouseEvent) => {
const element:Element = event.target as Element;
this.updateColor(element.classList[1].match(/d+/g));
})
});
}
}

其中 ApiService.requestsExample

是一个异步注释函数,它发出请求并返回响应。

代码几乎可以正常工作(例如,请求受到限制,按钮捣碎不会导致太多请求,颜色仍然会改变)

我正在努力弄清楚如何处理以下边缘情况: 1)我想保证最后触发的结果是接受响应的结果(假设响应返回),然后按时间顺序工作。由于请求是异步的,我不确定如何实现这一点? 2)(推论)为了防止更新时闪烁,我还想在以后的结果返回后丢弃从服务器返回的任何结果(基于问题顺序而不是响应顺序)。 3)一旦最后一个当前实时请求返回,我想丢弃所有正在进行的可观察量,因为我不再关心它们。

所以基本上,如果用户将两个按钮捣碎 20 秒,我希望发出 10 个请求,但除了切换按钮颜色外,将 UI 更新一次,并更新到正确的值。

此外,我只是希望得到任何关于是否有更好的方法可以通过可观察量实现此结果的反馈(或者即使可观察量是这项工作的正确工具!

让我们在下面解释一下 RxJS 5 示例:

  • 您希望updateServer响应式计算的一部分,因此请使其返回可观察量。
  • 由于您以相同的方式处理所有点击,因此mergeAll来自不同按钮的所有点击是有意义的。
  • 由于您仅使用按钮的索引进行计算,因此将点击次数map到该索引是有意义的。
  • 您可以立即updateColor作为副作用do.
  • debounceTime(1000)仅在一秒钟后发出单击,而没有其他单击。我认为这比Throttle好,因为如果用户进行多次快速单击,您不想进行不必要的网络调用。只有最后一个。
  • 由于您想在新点击时取消上一次updateServer,因此使用switchMap.它将点击映射到可观察的新updateServer,然后中止它,并在新点击到达时切换到新点击。
  • 由于您想忽略第一个updateServer后的所有进一步点击,或者这就是我的理解 3),take(1)将获取一个结果,然后完成整个链。
updateServer(index) {
return Observable.fromPromise(api.requestsExample(index))
}
this
.buttonObservables
.mergeAll()
.map(ev => ev.target.classList[1].match(/d+/g))
.do(idx => this.updateColor(idx))
.debounceTime(1000)
.switchMap(idx => this.updateServer(idx))
.take(1)
.subscribe(result => {
// update other divs
})

最新更新