Created
January 14, 2016 17:06
-
-
Save hannesstruss/011459f3ea6469be7c24 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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