Search code examples
monoproject-reactor

How to convert Reactor Map<Long, Mono<String>> to Mono<Map<Long, String>>


How to convert a map of Monos to a Mono emitting a Map containing each value?

  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();
  }

Solution

  • The full solution would be:

    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);
    }
    

    The flatMap is used to unwrap the entry from Flux<Entry<Long, Mono<String>>> to Flux<Tuple<Long, String>>. Finally, there are multiple collect operators available to get from reactive sequence to non-reactive sequence, e.g. collectMap.