Skip to content

Instantly share code, notes, and snippets.

@ian-ellis
Created January 18, 2017 01:04
Show Gist options
  • Save ian-ellis/6b7256d50ad0525d9a6da9ca028753c0 to your computer and use it in GitHub Desktop.
Save ian-ellis/6b7256d50ad0525d9a6da9ca028753c0 to your computer and use it in GitHub Desktop.
Reactive Data
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