首页 > 解决方案 > 如何避免在与 Obserables 的长轮询中重叠 HTTP 响应?

问题描述

我正在轮询我的数据库以获取异步作业的状态,如下所示:

handleProgress(job: AsyncJobDTO) {
    const finished: Subject<any> = new Subject<any>();
    this.progressService.startProgress();  

    Observable.interval(1000)
      .switchMap(() => this.http.get('/job_url/' + job.id))
      .takeUntil(finished)
      .subscribe((dto: AsyncJobDTO) => {

        if (dto.finishedAt) {
          finished.next();
          this.progressService.stopProgress();         
        }
    })
}

这很好用。

如果最后一个 HTTP 请求尚未响应,如何防止发送下一个 HTTP 请求?

标签: angularobservable

解决方案


添加一个标志,并实现如下逻辑。

interval(1000).subscribe(() => {
  if (!this.isRequesting) {
    this.isRequesting = true;
    this.http.get('/job_url/' + job.id).subscribe((dto: AsyncJobDTO) => {
      if (dto.finishedAt) {
        finished.next();
        this.progressService.stopProgress();
      }
      this.isRequesting = false;
    }, () => this.isRequesting = false);
  }
})

推荐阅读