Skip to content Skip to sidebar Skip to footer

Catch Http Response In Retrofit Before Passing It To The Calling Activity

Right now we are using retrofit like this: service.executeSomeRequest(UserPreferenceRequest userPreferenceRequest, new Callback() { @Override

Solution 1:

Your custom callback can process the response in the base class first and then delegate to an abstract method.

publicinterfaceStatusResponse {
  Status getStatus();
}

publicabstractclassCustomCallback<T extendsStatusResponse> implementsCallback<T> {
  @Overridepublicfinalvoidsuccess(T data, Response response) {
    if (data.getStatus() == Status.OK) {
      success(data);
    } else {
      // Handle error..
    }
  }

  publicabstractvoidsuccess(T data);
}

Solution 2:

You can combine the retrofit requests with an event bus and have a clean and centralised point for handling your responses.

All you need to do is define a Composed object like this:

publicclassGetUsers {
// Retrofit RequestpublicstaticfinalclassRequest {}

// Retrofit CallbackpublicstaticfinalclassCallbackimplementsretrofit.Callback<Response response> {

    @Overridepublicvoidsuccess(Response response, 
         Response retrofitResponse) {
         // .... handle the code
         BusManager.post(newEvent());
    }

    @Overridepublicvoidfailure(RetrofitError error) {}
         BusManager.post(newRetrofitErrorEvent(error));
    }

// Otto EventpublicstaticfinalclassEvent {}

This object defines the Request, Callback and Event and this object is feed to the retrofit request.

publicvoidgetUsers(){
     request.users(new GetUsers.Request(), new GetUsers.Callback());
 }

After this, in your main class looks like this:

publicvoidonResume(){    
   controller.getUsers();
}

@Subscribe
publicvoidonGetPostsEvent(GetPosts.Event event){
    textView.setText(event.getText());
}

For a more detailed explanation check this blog post: Otto + Retrofit – An elegant solution for Web Requests and you can find a working example here

Post a Comment for "Catch Http Response In Retrofit Before Passing It To The Calling Activity"