Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maybe switchIfEmpty lazy evaluation

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();
}
}
like image 680
nan Avatar asked Apr 18 '18 18:04

nan


1 Answers

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));
}
like image 180
nan Avatar answered Sep 20 '22 18:09

nan