Webflux collectMap 生成的 Mono<Map<String, Mono<String>>>

3

我在响应式编程领域还是新手。

我的代码看起来像这样:

    Flux.fromIterable(list)
                    .collectMap(a -> a.getName(),
                            b-> functionReturningMonoOfC(b)
                            .map(C::url)
                    .block();

结果的类型为Map<String, Mono<String>>。我希望它的类型为Map<String, String>。有什么想法吗?

1个回答

6

建议在将元素收集到Map之前使用flatMap操作符。

public class ReactorApp {

    record Person(String name){}

    public static Mono<String> functionReturningMono(Person person) {
        return Mono.just("Hello " + person.name());
    }

    public static void main(String[] args) {
        List<Person> persons = List.of(
                new Person("John"),
                new Person("Mike"),
                new Person("Stacey")
        );

        Map<String, String> result = Flux.fromIterable(persons)
                .flatMap(person -> functionReturningMono(person)
                        .map(String::toUpperCase)
                        .map(message -> Map.entry(person.name(), message)))
                .collectMap(Map.Entry::getKey, Map.Entry::getValue)
                .block();

        System.out.println("Result : " + result);
        // Result : {Mike=HELLO MIKE, Stacey=HELLO STACEY, John=HELLO JOHN}
    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接