将两个 Mono 和 return 第一个与第二个混合在一起

Mixing two Mono and return first one with second in firsts body

我面临的情况是,我必须使用 2 Mono,其中第二个将依赖于第一个的 Id 字段,return 第二个的响应在第一个 Mono 的主体中。

例如:

Mono<Article> first = fetchArticleById(id);

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

然后return结果为

/* 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());
});

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

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

求推荐。

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

map 函数中,您可以访问文章和评分,因此您可以根据需要连接它们。