reactive-programmingspring-webfluxproject-reactorspring-webclientspring-reactive

Call not propagating to the service method from Spring Reactive Controller


I am a beginner to the spring webflux. We are currently migrating our application to Spring Webflux. No I have stuck with a problem. The following is my scenario.

The main service class is calling the following service classes for data

StudentService - return Mono<Student>

StaffService - return Mono<Staff>

Here I have a wrapper class StudentWithMentor to store the result from these service classes.

public class StudentWithMentor {

    private Student student;
    private Staff mentor;
}

Now in controller I am calling the above 2 services and map it into 'StudentWithMentor' in the following way

Mono<StudentWithMentor> studentWithMentorMono = Mono.just(new StudentWithMentor());
        return studentWithMentorMono.map(s->{
            studentService.getStudentById(id)
            .doOnSuccess(s::setStudent)
            .doOnSuccess(st->staffService.getStaffByGrade(st.getGrade()));
            return s;
        });

But when I call this endpoint I am getting the following result in postman

{
    "student": null,
    "mentor": null
}

Note: I am getting result from the underlying services when I debugg. But the call is returning before it process.

How can I achieve this in a complete non-blocking way. Appreciates any help.


Solution

  • The easiest way will be to to use a zipWith operator to merge the results into StudentWithMentor object.

    See the code below:

    Mono<StudentWithMentor> studentWithMentorMono = studentService.getStudentById(id)
                .zipWhen(student -> staffService.getStaffByGrade(student.getGrade()), StudentWithMentor::new);