Spring Reactor Mono wait for the subscriber to complete it's task before returning the data

Viewed 1100

I am trying to execute the multiple HTTP calls with the Spring reactor webclient that returns the Mono. I am using Mono.block() to wait for all monos to complete. This is not waiting until the subscribe() complete.

public class UserValidator {

    public Mono<User> getUserSummary(int userId) {
        User user = new User();

        // First Mono
        Mono<Address> address = WebClientUtil.mono(userId, Address.class);
        address.subscribe(adrs -> updateAddress(adrs, user));

        // Second Mono
        Mono<Education> education = WebClientUtil.mono(userId, Education.class);
        education.subscribe(edcn -> updateEducationDeatils(edcn, user));

        Mono.when(address, education).block(); // Blocking the monos to complete

        // Intermittently returning the incomplete data ******************
        return Mono.just(user);
    }

    private void updateAddress(Address adrs, User user) {
        // Do some validations
        // Validations takes 5 to 10 seconds
        user.setAddress(adrs);
    }

    private void updateEducationDeatils(Education education, User user) {
        // Do some validations
        // Validations takes 5 to 10 seconds
        user.setEducation(education);
    }

}

Can someone please help me to fix this to return the updated User object after the subscribe() is completed?

1 Answers

You should not block Mono if the return value is Mono as well, use zip instead:

    public Mono<User> getUserSummary(int userId) {
        Mono<Address> addressMono = WebClientUtil.mono(userId, Address.class);
        Mono<Education> educationMono = WebClientUtil.mono(userId, Education.class);

        return Mono.zip(addressMono, educationMono, (address, education) -> {
          User user = new User();
          user.setAddress(address);
          user.setEducation(education);
        });
    }

Also, make sure your validation does not block either.

Related