Reputation: 943
I am writing a web server with extensive usage of reactive programming. I noticed that I forgot to check if Mono
is empty too many times. I am using WebFlux, so it converts an empty Mono
to a 200 OK
response, and it makes it very hard to detect these errors.
One way of reducing these mistakes is to make absence of a value explicit by using Mono<Optional<T>>
instead of Mono.empty()
.
This feels very similar to Optional
and null
debate, it even uses the same class. And while there are many people that are in favour of using Optional
and it is widely supported by libraries, I've yet to see anyone using Mono<Optional<T>>
.
Are there any drawbacks of using Mono<Optional<T>>
?
What is a better way to reliably handle cases of absent values?
Upvotes: 3
Views: 2349
Reputation: 3063
By using Mono<Optional<T>>
instead of Mono<T>
, you're putting yourself into a tricky situation of receiving an empty Mono
, but assuming that it will always have an instance of Optional
, so it doesn't really help, and only adds an unnecessary allocation.
There is a handy operator Mono#single, it will throw and error if you expected a non-empty Mono
, but got an empty one instead.
Upvotes: 4