0

I have the following code this returns a Mono<List> and I need a List

var test = repo.findAll().collectList().map( a-> {
                return a;
            });

spring.boot.version 2.7.0

  • 1
    Could you explain why you need a list? Blocking outside of tests means that your code becomes synchronous, so why not use a Flux instead? I'm quite sure the repo would return this in a findAll. A Flux can even be returned by the Controller without ever needing Lists. Otherwise if you don't leverage reactive programming practices, you could always use non-reactive libraries. – thinkgruen Jun 17 '22 at 22:31
  • As @thinkgruen says, better check why you need directly the list if you are using reactive programming – rekiem87 Jun 17 '22 at 22:56
  • My question is how can I use this information in my code? When I do this findall I need to use the information that I have in my database to map and save some information that I receive from another API. – Erick Gonzalez Jun 18 '22 at 15:44
  • By save you mean that you write something back to the database? That is also done reactively by R2DBC. when you call the API, you can leverage the reactive WebClient and to process it, Mono and Flux come with a map operation that you can use to work with whatever they are holding once it is ready. You can see that a lot of the concepts are taken from functional programming, so If you are comfortable with Streams and lambdas, reactive programming becomes much easier imo. – thinkgruen Jun 18 '22 at 19:01

1 Answers1

1

If repo.findAll().collectList().map( a-> {return a;}) returns a Mono<List<T>>, you can simply add .block() on the end to get back a List<T>

var test = repo.findAll().collectList().map( a-> {
             return a;
           }).block();

test will now just be a List

Your other option is to subscribe to it and pass in a Consumer that consumes the List. subscribe is a non-blocking operation. If you want to subscribe, you need to pass in a Consumer.

Consider this method, that takes a List<String> (making the assumption that you get a list of String, it can be a List of anything).

public void consume(List<String> strings) {

}

if that method is defined in the same class that your call is, you can simply do

repo.findAll().collectList().map( a-> { return a;}).subscribe(this::consume);

and it will pass the List<String> into your method when it's available.

lane.maxwell
  • 5,002
  • 1
  • 20
  • 30