Home > Mobile >  Mono: flatMap to load another item then return original item
Mono: flatMap to load another item then return original item

Time:06-04

I am just starting with Spring Webflux and I was wondering if the following call is a good way to load additional items in a reactive stream and if there is maybe another operator that can simplify this call:

Mono<Foo> fooMono = fooService.loadFoo();
fooMono.flatMap(foo -> barService.loadBarForFoo(foo).flatMap(bar -> Mono.just(foo)))

For example: fooMono might be something loaded via a WebClient and barService.loadBarFromFoo would know how to load a Bar given a Foo and then insert bar into foo. In the end I want to get foo back to perform some more actions, like loading another resource into foo.

Is it good practice to create a new Mono from foo in the end or is there maybe even another operator that can be used to simplify this?

CodePudding user response:

Hi you could use thenReturn supposing you do not need to use the result of loadBarForFoo method.

fooMono.flatMap(foo -> barService.loadBarForFoo(foo).thenReturn(foo));
  • Related