Search code examples
javareactive-programmingspring-webfluxproject-reactor

Mono not emitting items when using zipWhen operator (Java/Spring/Reactor)


I have the following methods:

Mono<User> doSomething1(String username) {
    return userService
                .getUser(username)
                .doOnError(error -> LOG.error(error.getMessage(), error));
  }

Mono<User> doSomething2(String username) {
    return userService
                .getUser(username)
                .zipWhen(this::processUser)
                .map(Tuple2::getT1)
                .doOnError(error -> LOG.error(error.getMessage(), error));
  }

Mono<Void> processUser(User user){
  return Mono.empty();
}

When I call doSomething1("test_user") I get a Mono with the expected user. However when I call doSomething2("test_user") the Mono simply completes without emitting any User item. Any idea why this is?


Solution

  • It happens because processUser returns Mono<Void> and technically there is nothing to zip with

    Here is a description of the zipWhen

    Wait for the result from this mono, use it to create a second mono via the provided rightGenerator function and combine both results into a Tuple2.

    In your case rightGenerator returns Mono.empty() and it completes the flow.

    Using zipWhen here is a little strange until you want to mutate User in processUser. I would rather use flatMap that is more natural here

     return userService
              .getUser(username)
              .flatMap(user -> 
                     processUser(user)
                        .thenReturn(user)
              )