How should I use Mono.zipWith when including a function that returns a Mono?

Viewed 9467

I have a Mono that I want to combine with another Mono, as in:

val firstMono = Mono.just("thing");
val secondMono = Mono.just("other thing");
val thirdMono = firstMono.zipWith(secondMono, function);

But I want the function to also return a Mono, without ending up with a Mono<Mono<?>>

The best I can come up with is:

val thirdMono = firstMono.zipWith(secondMono, function)
                          .flatMap(identity());

but that seems like a bit of a hack.

I also thought of

val thirdMono = firstMono.zipWith(secondMono)
                         .flatMap(function);

but in that case, I have to have the function accept a Tuple2 instead of the individual arguments, which is uglier.

Any thoughts?

1 Answers

I think your solution is good enough.

If you think that it seems like hack, you could place it in a separate utility method and change it when you find the better solution. Something like:

private static  <T1, T2, O> Function<Mono<T1>, Publisher<O>> flatZipTransformer(
        Mono<T2> p2, BiFunction<T1, T2, Mono<O>> function) {
    return p1 -> Mono.zip(p1, p2, function).flatMap(Function.identity());
}

Now you could use it like:

firstMono.transform(flatZipTransformer(secondMono, function))
Related