bertzzie
bertzzie

Reputation: 3568

Processing Optional Value from Mono in Project Reactor

I want to have a Mono that calls another async method that returns an Optional type to:

  1. have a value if the Optional is not empty,
  2. is MonoEmpty if the Optional value is empty.

Here's what I do right now:

Mono.fromCallable(() -> someApi.asyncCall()) .filter(Optional::isPresent) .map(Optional::get)

Obviously, this is not ideal since it uses two operators after the callable completed. If possible, I'd like to have the Mono.empty() or mono value from inside fromCallable.

What is the best way to achieve what I want?

Upvotes: 19

Views: 28422

Answers (3)

slisnychyi
slisnychyi

Reputation: 1980

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

Upvotes: 14

Roger Gouveia
Roger Gouveia

Reputation: 451

How about:

Optional<Integer> optional = Optional.of(5);
Mono<Optional<Integer>> monoWithOptional = Mono.just(optional);
Mono<Integer> monoWithoutOptional = monoWithOptional.flatMap(Mono::justOrEmpty);

Upvotes: 6

Ilya Zinkovich
Ilya Zinkovich

Reputation: 4410

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

Upvotes: 30

Related Questions