Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Mono and Optional together

One of the things I'm trying to wrap my head around with reactive programs is dealing with no results appropriately.

Let's say I had an API that optionally retrieved the latest order for a user. I want to leave the behavior of if there is no user found up to the caller. In plain old java, I would write something like:

Optional<Order> getLatestOrder(int userId) { ... }

In webflux, I'm trying to wrap my head around if an equivalent function should be returning Mono<Optional<Order>> or Mono<Order>.

If I add getLatestOrder() to a reactive flow, it might stop if I emit an empty mono. It feels weird also to do something like:

getLatestOrder().defaultIfEmpty(new Order());

since that now feels like just a sentinel value that's representing that it doesn't exist.

Is there guidance on a pattern with using Mono and Optional? Is there a proper way to ditch Optional completely when you really want to express something is not present?

like image 306
Ronnie76er Avatar asked Oct 26 '25 07:10

Ronnie76er


1 Answers

I started using webflux for a small project and we faced the same question. We decided to return Mono<Order> Most of the time we then use switchIfEmpty(Mono<? extends T> alternate) to throw an error or recover with an alternative

In our usecases switchIfEmpty() and defaultIfEmpty() give us enough control to handle empty results.

Example from the reference guide: https://projectreactor.io/docs/core/release/reference/index.html#_checking_the_execution_path_with_code_publisherprobe_code

like image 181
locohost Avatar answered Oct 28 '25 21:10

locohost



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!