如何结合 Mono 和 Flux 来创建一个对象?

问题描述

我想创建一个对象,该对象由 Mono 和 Flux 组成。 假设有 2 个服务 getPersonalInfogetFriendsInfoPerson 需要这两个服务来创建对象。压缩仅采用 friends 对象的第一个元素,因为只有一个 personalInfo,因为它是 Mono,但 friendsInfo 中可能有多个 friend 对象。我想将 friendsInfo 中的 friend 设置为 Person

class Person{
    String name;
    String age;
    List<Friend> friend;
}

Mono<PersonalInfo> personalInfo = personService.getPerson();// has name and age
Flux<Friend> friendsInfo = friendsService.getFriends();
// here I want to create Person object with personalInfo and friendsInfo
Flux<Person> person = Flux.zip(personalInfo,friendsInfo,(person,friend) -> new Person(person,friend));

解决方法

根据您的问题,我假设您想要创建一个 single 人对象,其中包含从您的 Mono<PersonalInfo> 填充的姓名和年龄,以及来自您的 Flux<Person> 的朋友列表。

您的尝试非常接近:

Flux<Person> person = Flux.zip(Person,Friend,(person,friend) -> new Person(person,friend));

特别是,zip 运算符的重载需要两个发布者和一个组合器,在这里使用是完全正确的。但是,有几件事需要改变:

  • 您想要一个单个 Person 对象,所以它应该是一个 Mono<Person>(和关联的 Mono.zip()
  • 根据评论,您需要将 Flux 转换为列表,您可以使用 collectList() 操作符进行此操作。

所以把它们放在一起,你最终会得到这样的结果:

Mono<Person> person = Flux.zip(personalInfo,friendsInfo.collectList(),(personalInfo,friendsList) -> new Person(personalInfo,friendsList));

...这应该给你你想要的东西。