I want to do something like below. In the Mono.fromCallable I run some block logic, then based on the value I either return Mono.empty() or the value so that it will either trigger the map or defaultIfEmpty.
Mono.fromCallable(() -> {
double number = Math.random();
if (number < 0.5) {
return Mono.empty();
}
return number;
})
.map(number -> 1)
.defaultIfEmpty(0)
This give an error since Mono.fromCallable expect a consistent return value. How do I adjust the code to make it work?
Although returning null
is usually prohibited in Reactor APIs, it is a valid value that Callable
may return, and Reactor handles it correctly by transforming into an empty Mono
:
Mono.fromCallable(() -> {
double number = Math.random();
if (number < 0.5) {
return null;
}
return number;
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With