RxJS链式调用:为最后一个switchMap请求实现5次定时轮询
解决RxJS链式调用中最后一步的轮询需求
你的问题核心是没正确实现轮询触发逻辑,原尝试代码只对单次请求做了延迟和过滤,没有重复发起请求的机制。以下是正确的实现方案:
正确代码实现
this.articleService.create(data).pipe( switchMap((article: ArticleCreateModel) => this.articleService.getArticle(article.id)), switchMap((article: ArticleCreateModel) => this.articleService.update({ ...article, timestamp: this.someFakeService.getData(), }), ), // 轮询逻辑实现 switchMap((article: ArticleCreateModel) => timer(0, 5000).pipe( take(5), // 最多发起5次请求 switchMap(() => this.articleService.createAsyncCommentsSection(article.id)), filter(res => !!res.hasSyncedWithOtherAPI), // 过滤出满足条件的响应 first() // 拿到第一个符合条件的结果就立即停止轮询 ) ), );
代码逻辑说明
timer(0, 5000):立即发起第一次请求,之后每隔5秒触发一次轮询take(5):限制最多发起5次请求,避免无限轮询switchMap(() => ...):每次轮询触发时调用目标接口filter(...):只保留hasSyncedWithOtherAPI为true的响应first():一旦获取到符合条件的响应,立即终止整个轮询流
原代码的问题分析
你之前的写法只对单次请求做了延迟和过滤:
- 仅发起一次
createAsyncCommentsSection请求,延迟5秒后输出 - 如果这次响应不满足
hasSyncedWithOtherAPI为true,filter会直接过滤掉结果,流就会终止,不会发起后续请求 take(5)在这里毫无意义,因为只有一次请求,根本不会产生5个结果
内容的提问来源于stack exchange,提问作者byCoder
相关产品推荐
相关产品推荐

