Search code examples
streamspring-webfluxreactive-programmingproject-reactorreactive

How can I combine the values from two publishers that are dependent on eachother?


I have the following methods

class A -> Flux<A> getAllA();
class B -> Mono<B> getB(A a);
class C -> Mono<C> getC(A a, B b)

Now Im trying to achieve the following using a Reactive Stream:

  1. Retrieve all A objects
  2. Create object B for every A
  3. Create object C for every pair A,B

Anyone know what this would look like? I came up with the solution below but was hoping there is some more elegant approach.

getAllA()
.map(a -> new Tuple2<A, B>(a, getB(a)))
.flatMap(t -> getC(t.getT1(), t.getT2()))

Solution

  • This is simple as:

    final Flux<C> flux = getAllA()
        .flatMap(
            a -> getB(a)
                .flatMap(
                    b -> getC(a, b)
                )
        );
    

    No need for Tuples at all. Behind the scenes the compiler will generate the necessary invokedynamic bytecode and LambdaMetafactory will do some heavy lifting for us to pass a to getC(a, b).