angular - Rxjs timeout() 运算符不在管道中工作
问题描述
嗨,我已经达到了以下代码的状态,除了超时之外,所有代码都在工作:
public monitorTask$(id: string): Observable<TaskResponse> {
return timer(0, 4000).pipe(
switchMap(() => this.fetchTaskStatus(taskId)),
timeout(120000),
takeWhile(res => this.isInProgress(res), true)
);
}
private postTask(id: string) {
this.monitorTask$(id).subscribe(
state => {
if (state.status === "SUCCESS") {
this.onSuccess();
}
if (state.status === "FAILURE) {
this.onFailure();
}
},
(err) => {
this.showError();
}
);
}
也试过这个:
public monitorTask$(id: string): Observable<TaskResponse> {
return interval(4000).pipe(
flatMap(() => this.fetchTaskStatus(id)),
takeWhile(res => this.isInProgress(res.status), true),
timeout(120000)
);
}
我期望超时出错并在 postTask() 中输入 (err) 块,但它永远不会达到超时。我一直在玩不同的变体,但似乎没有把它弄好。这是我拥有的最干净的一个,所以如果有人看到我缺少的东西,我会非常感激!
解决方案
这里有很多事情需要考虑。
- 发射间隔(
timer
4s)小于timeout
(120s)。所以timeout
永远不会触发,因为timer
每 4 秒发射一次。 - 将 a 管道
timeout
连接到 RxJS 内置 observabletimer
在逻辑上几乎没有意义。我相信你想通过管道timeout
传递给this.fetchTaskStatus()
函数。 - 在这种情况下,还有一个问题。这里使用的映射运算符是,当外部 observable ( ) 发出时
switchMap
,它将取消现有的内部 observable ( )。很可能您正在寻找运营商。但请注意,对于 的每次发射,都会单独触发。this.fetchTaskStatus()
timer
flatMap
timer
this.fetchTaskStatus()
public monitorTask$(id: string): Observable<TaskResponse> {
return timer(0, 4000).pipe(
flatMap(() =>
this.fetchTaskStatus(id).pipe(
timeout(120000)
)
),
takeWhile(res => this.isInProgress(res.status), true),
);
}
推荐阅读
- flutter - 没有为类 'String' 定义 getter 'todoText'
- graphql - 灯塔嵌套突变 FK 字段未填充
- python - 如何调用一个简单的函数并同时运行以下行?
- angular - ASP .Net Core 3.1 Angular 模板不起作用
- drupal-8 - 视图将字段暴露过滤器与多个分类术语结合在一起 Drupal 8
- python - num[:] 和 num 有什么区别?
- python - 如何使用 Selenium Webdriver 自动分页?
- react-native - 将原生视频反应为 GL 纹理
- regex - 使用正则表达式搜索一组单词,找到一些但不是全部
- android - Android:如何删除在为其项目设置比例后出现的recyclerview项目之间的空格?