0

I have the below code from the answer given in this [stackoverflow question]

bars = bars.flatMap(bar -> findByBarId(bar.getBarId())
                    .flatMap(foo -> {
                         bar.setIsInFoo(true);
                         return Mono.just(bar);
                    }).switchIfEmpty(Mono.just(bar)));

How to do above if I had single Mono<Bar> bar Mono<Foo> foo instead of Flux variant above and to get modified bar ?

ace
  • 11,526
  • 39
  • 113
  • 193

1 Answers1

2

Exact same logic should apply whether you start from Mono<Bar> bar or Flux<Bar> bars. The code can be simplified a bit inside the first flatMap to use map and defaultIfEmpty to avoid the overhead of intermediate Monos:

Mono<Bar> source;
Mono<Bar> updated = source
    .flatMap(bar -> findByBarId(bar.getBarId())
        .map(foo -> {
            bar.setIsInFoo(true);
            return bar;
         })
        .defaultIfEmpty(bar)
    );
Simon Baslé
  • 27,105
  • 5
  • 69
  • 70