Flux has multiple options to combine publishers. One of them is the zip operator.
Zip waits for each source to emit one element and combines these elements. The output emitted is a tuple with as many publishers wrapped inside the zip.
How does zip work?
The Zip operator will continue combining the outputs of sources until any of the sources completes.
This is an important point to remember when you are zipping publishers that emit different lengths of elements or if there are publishers that emit conditionally.
The following image helps with visualizing the behavior of Zip —
Let’s take a look at few examples:
Case 1 — Combining publishers that emit a single element
The above test runs successfully. No surprises here.
Case 2 — Combining publishers that emit multiple elements
The expected count in the above test is 2 since each publisher is emitting two values. Hence, each time zip emits a tuple of three values twice.
Output 1= Tuple(f11, f21, f31)
Output 2 = Tuple(f12, f22, f32)
Console output when I run the above test:
Verifying count:
Zip output f11,f21,f31
Zip output f12,f22,f32
Verifying values:
Zip output f11,f21,f31
Zip output f12,f22,f32
Case 3 — Combining publishers that emit different lengths of elements
Here I’m combining three publishers. Two of them emit two values and the third one emits a single value.
Note that the following test fails if I expect a count of 2 in the step verifier.
In this example, although f1 and f2 are emitting two values, we don’t see the values in the step verifier. There’s only one output since zip emits as soon as the shortest source is done emitting.
Console output when I run the above test:
Verifying count:
Zip output f11,f21,f31
Verifying values:
Zip output f11,f21,f31
Case 4 — Combining with a publisher that emits Void
This is similar to case-3 but here one of the publishers returns empty. In this case, the expected count is 0.
References:
https://www.vinsguru.com/reactive-programming-reactor-combining-multiple-sources-of-flux-mono/