Skip to content

Instantly share code, notes, and snippets.

@hannesstruss
Created January 14, 2016 17:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hannesstruss/011459f3ea6469be7c24 to your computer and use it in GitHub Desktop.
Save hannesstruss/011459f3ea6469be7c24 to your computer and use it in GitHub Desktop.
import android.util.Log;
import rx.Observable;
import rx.Observer;
class Either<T> {
private final T value;
private final Throwable throwable;
public static <T> Either<T> ofValue(T value) {
return new Either<>(value, null);
}
public static <T> Either<T> ofThrowable(Throwable throwable) {
return new Either<>(null, throwable);
}
private Either(T value, Throwable throwable) {
this.value = value;
this.throwable = throwable;
}
public boolean hasValue() {
return value != null;
}
public T getValue() {
return value;
}
public Throwable getThrowable() {
return throwable;
}
}
abstract class EitherSubscriber<T> implements Observer<T> {
@Override public void onCompleted() {
// do nothing
}
@Override public void onError(Throwable e) {
onEvent(Either.<T>ofThrowable(e));
}
@Override public void onNext(T t) {
onEvent(Either.ofValue(t));
}
public abstract void onEvent(Either<T> either);
}
class Main {
public static void main(String[] args) {
Observable.range(0, 100)
.subscribe(new EitherSubscriber<Integer>() {
@Override public void onEvent(Either<Integer> either) {
if (either.hasValue()) {
Log.d("TAG", "Cool! " + either.getValue());
} else {
Log.d("TAG", "Whoops! " + either.getThrowable().getMessage());
}
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment