Iterate Flux and concat with Mono in Spring Boot
I do have a fetchEmployment()
method which does successfully fetch the records and I am iterating over it to fetch the Mono object based on the worker id which successfully returns the object but I am not able to create the final Flux which should consist of WorkerDTO (list of WorkerDTO for normal Spring Boot application) but it returns the empty object i.e []
.
@Override
public Flux<WorkerDTO> method() {
Flux<EmployeeDTO> employmentDTOFlux = fetchEmployment();
Flux<WorkerDTO> workerDTOFlux = Flux.empty();
employmentDTOFlux.flatMap(employmentDTO -> {
Mono<WorkerDTO> worker = workerService.findWorkerById(employmentDTO.getWorkerId());
return Flux.concat(workerDTOFlux, Flux.from(worker));
});
return workerDTOFlux;
}
The following is simpler and should work as intended:
@Override
public Flux<WorkerDTO> method() {
return fetchEmployment().flatMap(employmentDTO -> {
workerService.findWorkerById(employmentDTO.getWorkerId());
});
}
I think you can rewrite this as something as simple as:
return fetchEmployment()
.map(EmployeeDTO::getWorkerId)
.flatMap(workerService::findWorkerById);