Handling null in RxJava 2.0

Josh Feinberg
Apr 23, 2017 · 2 min read
public class Optional<M> {

private final M optional;

public Optional(@Nullable M optional) {
this.optional = optional;
}

public boolean isEmpty() {
return this.optional == null;
}

public M get() {
if (optional == null) {
throw new NoSuchElementException("No value present");
}
return optional;
}
}
Observable.just(new Optional<>(null))
.subscribe(optional -> {
if (optional.isEmpty()) {
Log.d(TAG, "Object is null");
} else {
Log.d(TAG, "Object value is " + optional.get());
}
});
data class Optional<M>(val value : M?)
Observable.just(Optional(null)).subscribe({ optional ->
if
(optional.value == null) {
Log.d(TAG, "Object is null")
} else {
Log.d(TAG, "Object value is " + optional.value)
}
})
sealed class Optional<out T> {
class Some<out T>(val element: T): Optional<T>()
object None: Optional<Nothing>()
}
Observable.just(Optional.Some(1), Optional.None)
.subscribe({ optional ->
when
(optional) {
is Optional.Some -> {
Log.d(TAG, "Object value is " + optional.element)
}
is Optional.None -> {
Log.d(TAG, "Object is null")
}
}

})

Josh Feinberg

Written by

Lead Android Developer and Professional Sports Addict

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade