如何组合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
相关产品推荐
相关产品推荐

