代码之家  ›  专栏  ›  技术社区  ›  Tim

如何避免在长轮询中出现可观察的重叠http响应?

  •  0
  • Tim  · 技术社区  · 7 年前

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

    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请求?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Yong    7 年前

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

    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);
      }
    })
    
    推荐文章