我有一个轮询的用例,其中:
- 我想调用一个API,根据业务逻辑,立即返回数字(1-10)或错误(网络问题/ API异常等)(1.5-2秒)。
- 如果API返回错误(网络问题/ API异常等),则我希望取消订阅轮询并显示错误。
- 如果API返回成功,则我想检查返回值并取消订阅(如果返回值为5)或继续轮询。
- 我想每5秒调用一次API。
- 我想将轮询的最大时间(超时/阈值)保持为3分钟。如果在这3分钟内没有得到所需的响应(数字5),则轮询应该报错。
这是我目前的实现方式:
this.trackSpoke$ = interval(5000)
.pipe(
timeout(250000),
startWith(0),
switchMap(() =>
this.sharedService.pollForAPropertyValue(
"newuser"
)
)
)
.subscribe(
(data: SpokeProperty) => {
this.CheckSpokeStatus(data);
},
error => {
this.trackSpoke$.unsubscribe();
this.createSpokeState.CdhResponseTimedOut();
}
);
private CheckSpokeStatus(data) {
if (data.PropertyValue === "5") {
this.trackSpoke$.unsubscribe();
//display success
} else {
//keep the polling going
}
}
然而,上述实现没有超时。
需要做什么才能使其超时,以便我能够实现所有提到的用例?
interval(5000)
每隔5秒发出一次信号,因此紧接着的超时永远不会抛出错误,因为它每5秒接收一个值。 - martin