Spring Boot (v2.3.1): Webflux Mono Zip list of Monos

Viewed 2465

I am trying to figure out how to use this signature of .zip

public static <R> Mono<R> zip(final Iterable<? extends Mono<?>> monos, Function<? super Object[], ? extends R> combinator) {
    return onAssembly(new MonoZip<>(false, combinator, monos));
}

I have multiple monos create from webclient request that I would like zip up. Supplying each mono separately like so works:

Mono.zip(m1, m2, m3, (a, b, c) -> {  })

But if a List of monos like

List<Mono> monos = new ArrayList();

Mono.zip(monos, () -> {});

I get an error: List<Mono> is not compatible with Iterable<? extends Mono<?>>

Is it proper to attempt to use .zip is this manner and if so, how can I accomplish this.

1 Answers

I can see there are two things here:

  1. In the below signature, the first parameter has to of type Iterable<? extends Mono<?>> monos meaning your first param (monos) has to be of generic type Mono<?>, for example Mono.
  2. The second parameter has to be an array of objects, ie Object[]. So the (a, b, c) as the lambda expression params are not valid.
public static <R> Mono<R> zip(final Iterable<? extends Mono<?>> monos, Function<? super Object[], ? extends R> combinator) {
    return onAssembly(new MonoZip<>(false, combinator, monos));
}

A proper use of above method will be something like below:

List<Mono<YourObject>> monos = new ArrayList<>();
        Mono.zip(monos, objectArray ->
                Arrays.stream(objectArray)
                        .map(object -> yourMapperFunction(object))
                        .collect(Collectors.toList())
        );
Related