I use Maybe
switchIfEmpty
method to provide an alternate result if the source Maybe
is empty. However, I would like the alternate source to be executed only when the source is empty and not execute it when the source is not empty.
In the following example I would like to avoid execution of costlyFallback
if the source returned non-empty Maybe
. The current implementation always calls it because it is required to be passed to switchIfEmpty
method. Maybe.fromCallable
looks promising, however it will work only with callables which exludes returning a Maybe.empty
. Any hints are appreciated. Would be nice if switchIfEmpty
would accept some lazily evaluated Maybe
provider.
public class StartRxMaybe {
public static void main(String... args) {
System.out.println(new StartRxMaybe().start().blockingGet());
}
private Maybe<Integer> start() {
return func()
.switchIfEmpty(costlyFallback());
}
private Maybe<Integer> func() {
System.out.println("Non-empty maybe returned");
return Maybe.just(1);
}
private Maybe<Integer> costlyFallback() {
System.out.println("Fallback executed anyway");
return LocalDate.now().getMonth() == Month.JULY
? Maybe.just(2)
: Maybe.empty();
}
}
I think I found the solution. Using Maybe.defer
does the trick and allows to pass the supplier:
private Maybe<Integer> start() {
return func()
.switchIfEmpty(Maybe.defer(this::costlyFallback));
}
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