angular - 如何避免在与 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 请求?
解决方案
添加一个标志,并实现如下逻辑。
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);
}
})
推荐阅读
- php - 在表单中用作 GET 的多个 OPTION 值
- javascript - 从跨度到输入动态(onchange)操作值?
- python - 是否保证迭代相同的frozenset 总是以相同的顺序生成项目?(Python 3)
- maven - docker-maven-plugin:如何从`docker run ... -e 传递环境变量
` 构建或运行步骤? - r - 将我简单的“for循环”转换为应用函数
- c# - 如何移动到下一个 100 副本存储库?
- python - 在 python 中实现 if-then 逻辑时出现 TypeError 问题
- python - 继承(抽象)类时如何处理微小但影响深远的实现差异?
- c - 手动编译并与make链接后“找不到文件或文件夹”
- excel - 使用特定标准对 Excel 值进行分组