I'm trying to zip multiple sources of Maybe, but there is a possibility that one of it could be empty.
Maybe<ObjectA> aMaybe = Maybe.just("1");
Maybe<ObjectB> bMaybe = Maybe.empty();
return Maybe.zip(aMaybe, bMaybe, (a, b) -> {
return c = a + b;
});
Unfortunately this fails when the bMaybe
is empty
. What I'd like is for a way to zip and have the logic such that if there is no value, still try to do something.
RxJavaVersion - 2+ (The example I added is trivial, but what I have in actual code scenario is more complicated).
What I've tried which works?
The workaround is for me to have both of these as Single
and update the instance that is expected to be empty with a Single<Optional>
. This doesn't sit well with me. If I'm using a Single
I really want to expect a value to be there, going by RxJava's treatment of a Single
.
Alternatively I can use Maybe
with the same Optional
case, but now I'm stuck on the fact that an async type Maybe
is returning an Optional
. Maybe
already means there is maybe a value.
It seems like if there was a way I could zip with a Maybe.empty()
and recognize that there is no value and continue doing what I want to do, everything would work.
Yes, empty is error-like state in Maybe
, that is: it breaks the flow and results in empty. It's like NULL
in three-valued logic - one NULL
in any expression means that everything evaluates to NULL
(like in SQL).
Single<Optional<>>
is not a workaround, it expresses your intent of empty being a value like any other.
Maybe<Optional<>>
makes little sense in your case, unless your system has a clear and meaningful distinction between "no value" and "empty". Maybe.just(Optional.empty())
is very different from Maybe.empty()
, as you've already noticed.
There's no way to zip empty
any easier than a way to zip an error. You need to use switchIfEmpty
or materialize
to convert the flow-breaking state into regular flow, and then process that.