Skip to content

Instantly share code, notes, and snippets.

@ntakouris
Created March 13, 2018 13:52
Show Gist options
  • Save ntakouris/b5affe851c8680c2105d64fb59bac350 to your computer and use it in GitHub Desktop.
Save ntakouris/b5affe851c8680c2105d64fb59bac350 to your computer and use it in GitHub Desktop.
public class ApiResponseCallbackAdapter<T> implements Callback<ApiResponse<T>> {
Callback<T> callback;
public ApiResponseCallbackAdapter(Callback<T> callback) {
this.callback = callback;
}
@Override
public void onResponse(Call<ApiResponse<T>> call, Response<ApiResponse<T>> response) {
callback.onEverytime();
if (response == null) {
callback.onFailure(false);
return;
}
int responseCode = response.code();
if (responseCode >= 500) {
callback.onServerError(response);
return;
}
if (responseCode == 401) {
callback.onUnAuthorized();
return;
}
if (responseCode == 403) {
callback.onForbidden();
return;
}
if (responseCode >= 400) {
ApiResponse<T> responseBody = null;
try {
responseBody = new Gson().fromJson(response.errorBody().string(), ApiResponse.class);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (responseBody == null) {
callback.onFailure(false);
return;
}
callback.onBadRequest(responseBody.getErrors());
return;
}
}
callback.onSuccessfulResponse(response.body());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment