Search code examples
spring-bootproject-reactorreactor

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


Solution

  • 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();
                        }));