Created
January 18, 2017 01:04
-
-
Save ian-ellis/6b7256d50ad0525d9a6da9ca028753c0 to your computer and use it in GitHub Desktop.
Reactive Data
This file contains hidden or 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
public class ReactiveData<T> { | |
@Getter | |
private final T value; | |
@Getter | |
private final Throwable error; | |
public ReactiveData(T value) { | |
this.value = value; | |
this.error = null; | |
} | |
public ReactiveData(Throwable error) { | |
this.value = null; | |
this.error = error; | |
} | |
public ReactiveData(T value, Throwable error) { | |
this.value = value; | |
this.error = error; | |
} | |
public boolean hasError() { | |
return error != null; | |
} | |
public boolean noError() { | |
return error == null; | |
} | |
} | |
public static <T, R> Observable.Transformer<T, ReactiveData<R>> switchMapReactiveData(Func1<T, Observable<R>> onwardCall) { | |
return new Observable.Transformer<T, ReactiveData<R>>() { | |
private R previousValue = null; | |
@Override | |
public Observable<ReactiveData<R>> call(Observable<T> observable) { | |
return observable.switchMap( | |
a -> onwardCall.call(a) | |
.doOnNext(value -> previousValue = value) | |
.map(ReactiveData::new) | |
.onErrorReturn(e -> new ReactiveData<>(previousValue, e)) | |
); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment