Issue
Somewhat new to reactive programming and can't find any good examples of this. How would I combine results from a Mono and a Flux (concurrent fetches) to return a Mono of a DTO?
I know the code below won't compile but generally speaking I want to do something like the below.
Thanks in advance.
public Mono<UserDto> getByName(String name) {
Mono<User> user = userRepo.findByName(name);
Flux<PhoneNumber> numbers = phoneNumbersRepo.findByName(name);
return Mono.zip(user, number) ...
UserDto dto = new UserDto();
dto.setFirstName(user.getFirstName());
dto.setPhoneNumbers(number);
}
Solution
You would need to transform Flux<PhoneNumber>
into Mono<List<PhoneNumber>>
and then combine using Mono.zip
public Mono<UserDto> getByName(String name) {
Mono<User> user = userRepo.findByName(name);
Flux<PhoneNumber> numbers = phoneNumbersRepo.findByName(name);
return Mono.zip(user, numbers.collectList())
.map(res -> {
UserDto dto = new UserDto();
dto.setFirstName(res.getT1().getFirstName());
dto.setPhoneNumbers(res.getT2());
return dto;
});
}
Answered By - Alex
Answer Checked By - Marilyn (JavaFixing Volunteer)