Reputation: 339
I have created a List of String Monos List<Mono<String>> myList
. And now I need to concatenate them in a big string.
When I initialize a StringBuilder
and update it asyncronously, the empty line maybe returned.
//method body....
StringBuilder builder = new StringBuilder();
myList.forEach {
mono ->
mono.map{ str -> builder.append(str)}
}
return builder.toString() //<- is ""
How can I make the builder wait for the monos?
Upvotes: 2
Views: 3045
Reputation: 1838
The best way is to convert List of Monos to Flux and then reduce your flux to have one string which contains all your substrings. Then you have Mono that you can use still in async way. (You should always work on Mono/Flux if you want to keep async paradigm with project reactor)
Example:
List<Mono<String>> listOfMonosWithString = Arrays.asList(Mono.just("a"), Mono.just("b"), Mono.just("c"));
Flux<String> mergedMonos = Flux.fromIterable(listOfMonosWithString)
.flatMapSequential(Function.identity());
mergedMonos
.reduce(String::concat)
.doOnNext(System.out::println)
.subscribe();
Upvotes: 2