如何将 Reactor Map<Long, Mono<String>> 转换为 Mono<Map<Long, String>>
How to convert Reactor Map<Long, Mono<String>> to Mono<Map<Long, String>>
如何将 Monos 的映射转换为发射包含每个值的映射的 Mono?
private Mono<Map<Long, String>> convertMonoMap(Map<Long, Mono<String>> monoMap) {
// TODO what comes here?
}
@Test
public void testConvert() {
Map<Long, Mono<String>> input = Map.of(1L, Mono.just("1"), 2L, Mono.just("2"));
Map<Long, String> expected = Map.of(1L, "1", 2L, "2");
Mono<Map<Long, String>> output = convertMonoMap(input);
StepVerifier.create(output).expectNext(expected).verifyComplete();
}
完整的解决方案是:
private Mono<Map<Long, String>> convertMonoMap(Map<Long, Mono<String>> monoMap) {
return Flux.fromIterable(monoMap.entrySet())
.flatMap(entry -> entry.getValue().map(
value -> Tuples.of(entry.getKey(), value))
).collectMap(Tuple2::getT1, Tuple2::getT2);
}
flatMap
用于解包从 Flux<Entry<Long, Mono<String>>>
到 Flux<Tuple<Long, String>>
的条目。最后,有多个收集运算符可用于从反应序列到非反应序列,例如collectMap
.
如何将 Monos 的映射转换为发射包含每个值的映射的 Mono?
private Mono<Map<Long, String>> convertMonoMap(Map<Long, Mono<String>> monoMap) {
// TODO what comes here?
}
@Test
public void testConvert() {
Map<Long, Mono<String>> input = Map.of(1L, Mono.just("1"), 2L, Mono.just("2"));
Map<Long, String> expected = Map.of(1L, "1", 2L, "2");
Mono<Map<Long, String>> output = convertMonoMap(input);
StepVerifier.create(output).expectNext(expected).verifyComplete();
}
完整的解决方案是:
private Mono<Map<Long, String>> convertMonoMap(Map<Long, Mono<String>> monoMap) {
return Flux.fromIterable(monoMap.entrySet())
.flatMap(entry -> entry.getValue().map(
value -> Tuples.of(entry.getKey(), value))
).collectMap(Tuple2::getT1, Tuple2::getT2);
}
flatMap
用于解包从 Flux<Entry<Long, Mono<String>>>
到 Flux<Tuple<Long, String>>
的条目。最后,有多个收集运算符可用于从反应序列到非反应序列,例如collectMap
.