我正在轮询数据库以获取异步作业的状态,如下所示:
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请求?
添加一个标志,并实现如下逻辑。
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); } })