Processing Optional Value from Mono in Project Reactor
How about:
Optional<Integer> optional = Optional.of(5);
Mono<Optional<Integer>> monoWithOptional = Mono.just(optional);
Mono<Integer> monoWithoutOptional = monoWithOptional.flatMap(Mono::justOrEmpty);
Mono have justOrEmpty
method that you can use with Optional<? extends T>
type. When Optional.empty() == true
we would have MonoEmpty
.
Create a new Mono that emits the specified item if Optional.isPresent() otherwise only emits onComplete.
Mono<String> value = Mono.justOrEmpty(someApi.asyncCall());
There is an alternative with flatMap
that's a bit better than Optional.isPresent
and Optional.get
that can lead to accidentally calling get on empty Optional
:
Mono.fromCallable(() -> someApi.asyncCall())
.flatMap(optional -> optional.map(Mono::just).orElseGet(Mono::empty))