You need to enable JavaScript to run this app. 如何组合Mono与Flux来构造包含个人信息和好友列表的Person对象
优惠活动
大模型
产品
解决方案
定价
更多

如何组合Mono与Flux来构造包含个人信息和好友列表的Person对象

问题原因

你原来的写法用Flux.zip是按元素一一对应配对,Mono<PersonalInfo>只会发射1次数据,所以只会和Flux<Friend>的第一个元素配对,最终只能得到带单个好友的Person,不符合需求。

解决方案

先把返回多个好友的Flux<Friend>通过collectList()方法转换为一次性返回全量好友列表的Mono<List<Friend>>,再用Mono.zip配对两个Mono结果构造完整Person即可:

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

Mono<PersonalInfo> personalInfo = personService.getPerson();// 包含name和age字段
Flux<Friend> friendsInfo = friendsService.getFriends();

// 调整后实现
Mono<Person> person = Mono.zip(
        personalInfo,
        friendsInfo.collectList(), // 收集所有Friend为List,转换为Mono
        (pInfo, friendList) -> {
            Person person = new Person();
            person.setName(pInfo.getName());
            person.setAge(pInfo.getAge());
            person.setFriend(friendList);
            return person;
        }
);

如果Person类存在对应参数的构造方法,可以直接简化组合函数的写法。

内容的提问来源于stack exchange,提问作者koukou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 12:36:00