Catch http response in Retrofit before passing it to the calling activity

后端 未结 2 648
南旧
南旧 2020-12-30 12:15

Right now we are using retrofit like this:

service.executeSomeRequest(UserPreferenceRequest userPreferenceRequest, new Callback         


        
相关标签:
2条回答
  • 2020-12-30 12:24

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

    public interface StatusResponse {
      Status getStatus();
    }
    
    public abstract class CustomCallback<T extends StatusResponse> implements Callback<T> {
      @Override public final void success(T data, Response response) {
        if (data.getStatus() == Status.OK) {
          success(data);
        } else {
          // Handle error..
        }
      }
    
      public abstract void success(T data);
    }
    
    0 讨论(0)
  • 2020-12-30 12:39

    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:

    public class GetUsers {
    // Retrofit Request
    public static final class Request {}
    
    // Retrofit Callback
    public static final class Callback 
          implements retrofit.Callback<Response response> {
    
        @Override
        public void success(Response response, 
             Response retrofitResponse) {
             // .... handle the code
             BusManager.post(new Event());
        }
    
        @Override
        public void failure(RetrofitError error) {}
             BusManager.post(new RetrofitErrorEvent(error));
        }
    
    // Otto Event
    public static final class Event {}
    

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

     public void getUsers(){
         request.users(new GetUsers.Request(), new GetUsers.Callback());
     }
    

    After this, in your main class looks like this:

    public void onResume(){    
       controller.getUsers();
    }
    
    @Subscribe
    public void onGetPostsEvent(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

    0 讨论(0)
提交回复
热议问题