Correct me if I'm wrong but I've found no way to accomplish this.
I want to flatMap a Maybe into a Single while when the value is present I want to get it in the Mapper. If there's an error it'll just delegate it to the Single and skip the mapper entirely. However when the Maybe is empty I want the mapper function to get called with null so I know it's empty.
MaybeFlatMapSingle already does almost all of the job. However here I'd like the mapper to get called instead with null.
Obviously the above mentioned behavior can be accomplished by flatMapping and then recovering with onError functions in case of NoSuchElementException however I feel like there is a need for having this as a standard operator.
Happy to provide a PR for this.
That is an uncommon behavior with very peculiar API design thus it would be better for it to live outside RxJava.
Is it? In general I find it hard to continue working with a Maybe once it's empty. There's not an easy way to transform it into a non optional reactive type again.
I've got a Maybe<Location> currentLocation() method, which might give me the location if the user has granted the permission for the app, if not it'll be an empty Maybe. Now I'd like to continue with a backend request and in case there is a location, send it to the backend and if there isn't just send the request without the location. (The location in this case is not crucial for the request.)
Instead of using null you could also use some object to represent 'no location'. Then you could do something like:
currentLocation()
.switchIfEmpty(Maybe.just(Location.ABSENT))
.toSingle()
.map(l -> {
if (l.equals(Location.ABSENT))
foo();
else
bar();
});
The mapper is always called...
This defeats the purpose then every caller needs to know about the absent value plus even I can also just use a single in the first place.
Using nulls sounds really bad... how about
currentLocation().flatMapSingle(l -> requestWithLocation(l)).
switchIfEmpty(Maybe.defer(() -> requestWithoutLocation()))
I don't want the public API of this important operator to make the users rely on null.
Using nulls sounds really bad... how about
currentLocation().flatMapSingle(l -> requestWithLocation(l)). switchIfEmpty(Maybe.defer(() -> requestWithoutLocation()))
Just a reminder
use flatMapSingleElement instead of flatMapSingle for chaining with switchIfEmpty
Most helpful comment
Instead of using
nullyou could also use some object to represent 'no location'. Then you could do something like:The mapper is always called...