首页 > 解决方案 > 混合两个 Mono 并返回第一个与第一个主体中的第二个

问题描述

我面临一种情况,我必须使用 2 Mono,其中第二个将依赖于第一个的 Id 字段并在第一个 Mono 的正文中返回第二个的响应。

例如 :

Mono<Article> first = fetchArticleById(id);

Mono<Rating> second = fetchRating(article.getRatingId()); //here I will use the response from 
first Mono,

然后将结果返回为

/* this is the response of first Mono, the rating field is set by second Mono */
Article {
"id":1234,
"text" : "some text",
"rating" : "5 star", //fetched from second Mono
"ratingId":qq11
}

我试过了

first.map(art -> {
 return fetchRating(art.getRatingId());
});

但是像这样,我只能返回第二个 Mono 的响应。

通过尝试 Map 或 Flatmap,它仅适用于第二个单声道。

请建议。

标签: reactive-programmingspring-webfluxproject-reactor

解决方案


fetchArticleById(id)
  .flatMap(art -> fetchRating(art.getRatingId())
    .map(rating -> new Pair(art, rating))); 

在该map功能中,您可以访问文章和评级,因此您可以根据需要连接它们。


推荐阅读