Retrofit 2 is one the best library I have used it so far. There are many cases in which we can use custom callback for our response callback such as Error Handling, Response Handling, Custom Response and much more.
By using a custom callback or any piece of custom code in an application we are promoting object oriented design pattern and thus reducing your efforts that are needed/mandatory to follow if not using it.
Here is an example of Custom Callback that is used to handle error , hide dialog and return response data to original callback.
How it is helpful?
By using Custom Callback, we are preventing from extra effort required to handle error in each request. Plus, we can perform custom operation that are required whenver the response is recieved. In this case we are just hidding the AlertDialog.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public class RetrofitCallback<T> implements Callback<T> { @SuppressWarnings("unused") private static final String TAG = "RetrofitCallback"; private Context mContext; private final Callback<T> mCallback; public RetrofitCallback(Context context, Callback<T> callback) { mContext = context; this.mCallback = callback; } @Override public void onResponse(Call<T> call, Response<T> response) { // Do application relavent custom operation like manupulating reponse etc. AlertDialogHelper.dismiss(mContext); mCallback.onResponse(call, response); } @Override public void onFailure(Call<T> call, Throwable t) { // Handle error etc. NetworkHelper.onFailure(t, (Activity) mContext); mCallback.onFailure(call, t); } } |
We can use this callback instead of our existing callback. e.g.
1 |
RetrofitClient.getClient().create(ApiInterface.class).getHomePageData().enqueue(new RetrofitCallback<>(SplashScreenActivity.this, mHomePageResponseCallback)); |
And Here is the original callback which gets called from our Custom RetrofitCallback
1 2 3 4 5 6 7 8 9 10 11 |
private Callback<HomePageResponse> mHomePageResponseCallback = new Callback<HomePageResponse>() { @Override public void onResponse(Call<HomePageResponse> call, Response<HomePageResponse> response) { // Handle response data } @Override public void onFailure(Call<HomePageResponse> call, Throwable t) { // i don't think that would be required right now as the Error is already handled in Custom Callback } }; |
That’s all it take for laziness!