Home > OS >  convert to Mono<List<String>> from Flux<List<String>> in Java
convert to Mono<List<String>> from Flux<List<String>> in Java

Time:04-21

I have this entity class.

public class MyClass {

    private String category;

    private List<String> topics;

}

I am using firestore database with spring reactive. I am trying to return all topics from all categories in a list in a controller but getting an empty list return. Here is my controller method. Here 'getTopics' return a list of topics.

 @GetMapping("/alltopics")
 public Mono<List<String>> getAllTopics() {
     List<String> topics = new ArrayList<>();
     repository.findAll().map(MyClass::getTopics).subscribe(topics::addAll);
     return Mono.just(topics);
    }

CodePudding user response:

The Project Reactor documentation is really good. You want to aggregate a Flux; I suggest using reduce(), something like

import java.util.stream.Collector;
import java.util.List;
import java.util.LinkedList;

...

@GetMapping("/alltopics")
public Mono<List<String>> getAllTopics() {
    return repository.findAll()
            .map(MyClass::getTopics)
            .reduce(new LinkedList(),
                (result, topics) -> {
                    result.addAll(topics));
                    return result;
                });
}
  • Related