Mark O
Mark O

Reputation: 1167

Spring reactor join 2 Mono

I need to connect to database in reactive way using spring reactor. Here is scenario which I would like to get->

  1. 1.Connect to db and get response1

    2.Then Connect to db and get response2 while providing response1.parameter

    1. Join those two into single response and send back to the user as String

Since all objects are unique I planned to use Mono

Mono<Response1> r1 = qrepo.findByID(id)
Mono<Response2> r2 = qrepo.findByID(r1.getParam())

Mono<String> combined = Mono.when(r1, r2).map(t -> { 
            StringBuffer sb = new StringBuffer();
                sb.append(r1.getProp1());
                sb.append(r2.getProp2());

But this doesn't wor for me

Upvotes: 0

Views: 4725

Answers (2)

Radhakrishnan CH
Radhakrishnan CH

Reputation: 129

Use Mono.zip

Example:

Mono.zip(Mono.just("hello"), Mono.just("world")).map(tuple2 -> {

      return tuple2.getT1() + tuple2.getT2();
    });

Mono.zip aggregate given monos into a new Mono that will be fulfilled when all of the given Monos have produced an item.

Upvotes: 3

Alexander Pankin
Alexander Pankin

Reputation: 3955

You should get response1 then flatMap its result to access parameter and pass it to repository then map result to string

    Mono<String> resultMono = qrepo.findByID(id)
            .flatMap(response1 -> qrepo.findByID(response1.getParam())
                    .map(response2 -> {
                        StringBuilder sb = new StringBuilder();
                        sb.append(response1.getProp1());
                        sb.append(response2.getProp2());
                        return sb.toString();
                    }));

Upvotes: 6

Related Questions