Skip to content

Instantly share code, notes, and snippets.

@Artur-Sulej
Created November 24, 2015 23:55
Show Gist options
  • Save Artur-Sulej/9905070fa3d91c829817 to your computer and use it in GitHub Desktop.
Save Artur-Sulej/9905070fa3d91c829817 to your computer and use it in GitHub Desktop.
RequestCallback - a subclass of Retrofit's Callback class. Makes things simpler by taking care of showing and hiding progress view (for example animated spinner) and providing higher level of abstraction with its callbacks.
public enum HttpStatus {
UNAUTHORIZED(401),
FORBIDDEN(403),
NOT_FOUND(404),
OTHER_ERROR(null);
private static HashMap<Integer, HttpStatus> map;
private Integer code;
HttpStatus(Integer code) {
this.code = code;
}
public static HttpStatus getStatusByCode(Integer code) {
if (map == null) {
initializeMapping();
}
if (map.containsKey(code)) {
return map.get(code);
}
HttpStatus otherError = OTHER_ERROR;
OTHER_ERROR.setCode(code);
return otherError;
}
private static void initializeMapping() {
map = new HashMap<Integer, HttpStatus>();
for (HttpStatus httpStatus : HttpStatus.values()) {
map.put(httpStatus.code, httpStatus);
}
}
public Integer getCode() {
return code;
}
private void setCode(Integer code) {
this.code = code;
}
}
public interface LoadingUI {
void showProgressView();
void hideProgressView();
void onNetworkErrorOccurred();
void onGenericErrorOccurred();
}
public abstract class RequestCallback <T> implements Callback<T> {
private LoadingUI ui;
private boolean shouldUseProgressView = true;
public RequestCallback(LoadingUI ui) {
this.ui = ui;
}
public RequestCallback(LoadingUI ui, boolean shouldUseProgressView) {
this.ui = ui;
this.shouldUseProgressView = shouldUseProgressView;
}
public abstract void onSuccess(T body, Response response);
public abstract void onErrorOccurred(HttpStatus statusCode);
@Override
public final void onResponse(Response<T> response, Retrofit retrofit) {
if (response.isSuccess()) {
onSuccess(response.body(), response);
} else {
onErrorOccurred(HttpStatus.getStatusByCode(response.code()));
}
tryHideProgressView();
}
protected void tryHideProgressView() {
if (shouldUseProgressView) {
ui.hideProgressView();
}
}
@Override
public final void onFailure(Throwable throwable) {
if (throwable instanceof IOException) {
onNetworkErrorOccurred();
} else {
onGenericErrorOccurred();
}
tryHideProgressView();
}
protected void onNetworkErrorOccurred() {
ui.onNetworkErrorOccurred();
}
protected void onGenericErrorOccurred() {
ui.onGenericErrorOccurred();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment