Search code examples
javaspringspring-webfluxreactive-programmingproject-reactor

How to execute concurrent void method calls


I'm working with a database and trying to figure out how I can concurrently execute writes which have a void return type. I've already wrapped the blocking calls as per the docs.

I want to:

  1. Get the item from the database which returns a Mono<ObjectToReturn>
  2. Concurrently call 2 methods which return Mono<Void> which I need to complete before I return
  3. Return the response from get() to the subscriber

Functionally I have this working with:

    return repository
            .get(param)
            .flatMap(response -> Mono.zip(
                    method1(response),
                    method2(response),
                    (x, y) -> response
            ))

However:

  • I feel like I'm abusing Mono.zip to subscribe to the response since I'm ignoring x and y

  • I've had to change the method1/2 interfaces to arbitrarily return a value after the write is successful

What's the right way of doing this?


Solution

  • The problem with your code is that if any mono is empty, the zip operation won't emit any value, resulting in no output.

    I think it is better to use .thenReturn() fallback:

     return repository.get(param)
                      .flatMap(response -> Mono.zip(method1(response), method2(response))
                            .thenReturn(response)
                      )
    

    The response will be returned after Mono.zip is completed