Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Mono.empty() from Mono.fromCallable

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?

like image 998
user3908406 Avatar asked Sep 19 '25 18:09

user3908406


1 Answers

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;
})
like image 103
bsideup Avatar answered Sep 21 '25 11:09

bsideup