Skip to content

Instantly share code, notes, and snippets.

@iamdeveloper-lopez
Last active October 25, 2018 04:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamdeveloper-lopez/a5f17b187151546f0a59c7a0ad8130db to your computer and use it in GitHub Desktop.
Save iamdeveloper-lopez/a5f17b187151546f0a59c7a0ad8130db to your computer and use it in GitHub Desktop.
Alternative to Rx request using Retrofit

RetrofitTask

To implement it with custom callback just call

Call<GitHubUser> call = githubService.getUser(userId);

RetrofitTask task = new RetrofitTask<GitHubUser>(call, new RetrofitTask.RetrofitTaskCllback<GitHubUser>(){
    @Override
    public void onSuccess(GitHubUser response) {
        //Do Something
    }
    
    @Override
    public void onFailed() {
        //Do Something
    }
});
task.execute();

To implement it with default callback just call

Call<GitHubUser> call = githubService.getUser(userId);

RetrofitTask task = new RetrofitTask<>(call, new retrofit2.Callback<GitHubUser>() {
                @Override
                public void onResponse(@NonNull Call<GitHubUser> call, @NonNull Response<GitHubUser> response) {
                    //Do Something
                }

                @Override
                public void onFailure(@NonNull Call<GitHubUser> call, @NonNull Throwable t) {
                    //Do Something
                }
            });
task.execute();

For error handling you can just look at this : https://futurestud.io/tutorials/retrofit-2-simple-error-handling

public class RetrofitTask<T> extends AsyncTask<Void, Void, Object> {
private static final String TAG = RetrofitTask.class.getSimpleName();
private Callback<T> defaultCallback;
private RetrofitTaskCallback<T> callback;
private Call<T> call;
public void execute() {
super.execute();
}
public RetrofitTask(Call<T> call, RetrofitTaskCallback<T> callback) {
this.call = call;
this.callback = callback;
}
public RetrofitTask(Call<T> call, Callback<T> defaultCallback) {
this.call = call;
this.defaultCallback = defaultCallback;
}
@Override
protected Object doInBackground(Void... voids) {
try {
return call.execute();
} catch (Exception e) {
return e;
}
}
@Override
protected void onPostExecute(Object o) {
if (o instanceof Exception) {
if (defaultCallback != null)
defaultCallback.onFailure(call.clone(), (Exception) o);
if (callback != null)
callback.onFailed();
} else {
Response<T> response = (Response<T>) o;
if (defaultCallback != null)
defaultCallback.onResponse(call.clone(), response);
if (response.isSuccessful()) {
if (callback != null)
callback.onSuccess(response.body());
} else {
if (callback != null)
callback.onFailed();
}
}
}
public interface RetrofitTaskCallback<T> {
void onSuccess(T response);
void onFailed();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment