RxJS:在最后一个switchMap中进行轮询的调用链



我有一个非常复杂的例子,用很多switchMap等链接RxJS调用。在我面临一个要求之前,一切都很清楚:我需要每5秒轮询一次最后的请求,直到响应对象包含一个值。我有点卡住了。。。如果我只有轮询或只有普通的switchMap,我知道如何做到这一点。

this.articleService.create(data).pipe(
switchMap((article: ArticleCreateModel) => this.articleService.getArticle(article.id)),
switchMap((article: ArticleCreateModel) =>
this.articleService.update({
...article,
timestamp: this.someFakeService.getData(),
}),
),
// somehow I need to poll next createAsyncCommentsSection every 5 sec until response object key is let's say 'true'
switchMap((article: ArticleCreateModel) => this.articleService.createAsyncCommentsSection(article.id)),
);

我如何每隔5秒轮询最后一个switchMap,直到响应对象键为true。只重试5次?

我试过了,但看起来不起作用:

switchMap((article: ArticleCreateModel) =>
this.articleService.createAsyncCommentsSection(article.id).pipe(
delay(5000),
filter((article: ArticleCreateModel) => !!article.hasSyncedWithOtherAPI),
take(5),
),
),

您可以创建一个单独的可观察对象,当response.isComplete像这样时进行轮询和发射:

timer(0, 5000).pipe(
take(5),
switchMap(() => this.articleService.createAsyncCommentsSection(articleId)),
filter(response => response.isComplete),
first()
);

timer()将立即发射,然后每5秒发射一次;得益于CCD_ 6,最多5次。

filter可防止排放,直到满足您的条件。

first将只进行1次发射,但如果在流完成之前没有接收到发射,则会抛出错误。

总的来说,可能看起来是这样的:

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),
switchMap(() => this.articleService.createAsyncCommentsSection(article.id)),
filter(response => response.isComplete),
first()
)
);

最新更新