Skip to content

Instantly share code, notes, and snippets.

@kalpeshp0310
Last active April 20, 2017 12:55
Show Gist options
  • Save kalpeshp0310/3c615e5428270bdacc8251c62dee3780 to your computer and use it in GitHub Desktop.
Save kalpeshp0310/3c615e5428270bdacc8251c62dee3780 to your computer and use it in GitHub Desktop.
Retrofit CallAdapter for Rx Errors.
public class RxErrorCallAdapterFactory extends CallAdapter.Factory {
@Override
public CallAdapter<?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
Class<?> rawType = getRawType(returnType);
String canonicalName = rawType.getCanonicalName();
boolean isSingle = rawType == Single.class;
boolean isCompletable = rawType == Completable.class;
// Return type not a Rx type.
if (rawType != Observable.class && !isSingle && !isCompletable) {
return null;
}
CallAdapter delegate = retrofit.nextCallAdapter(this, returnType, annotations);
if (isCompletable) {
return new CallAdapter<Completable>() {
@Override public Type responseType() {
return delegate.responseType();
}
@Override public Completable adapt(Call call) {
return ((Completable) delegate.adapt(call)).onErrorResumeNext(
throwable -> Completable.error(convertToDomainSpecificException(throwable)));
}
};
} else if (isSingle) {
return new CallAdapter<Single<?>>() {
@Override public Type responseType() {
return delegate.responseType();
}
@Override public Single<?> adapt(Call call) {
return ((Single<?>) delegate.adapt(call)).onErrorResumeNext(
throwable -> Single.error(convertToDomainSpecificException(throwable)));
}
};
} else {
return new CallAdapter<Observable<?>>() {
@Override public Type responseType() {
return delegate.responseType();
}
@Override public Observable<?> adapt(Call call) {
return ((Observable<?>) delegate.adapt(call)).onErrorResumeNext(
throwable -> Observable.error(convertToDomainSpecificException(throwable)));
}
};
}
}
private Throwable convertToDomainSpecificException(Throwable throwable) {
if (throwable instanceof HttpException) {
Response response = ((HttpException) throwable).response();
return DomainException.create(response);
}
return throwable;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment