How can I update Activity/Fragment UI from Retrofit onResponse()?

前端 未结 2 749
执念已碎
执念已碎 2021-01-23 06:13

I want to use Retrofit 2.1.0 for my next Android project. I would like to use Design Pattern and therefore create separate classes for every REST call i.e

IBalanceServ

相关标签:
2条回答
  • 2021-01-23 06:38
     public class BalanceRestClient {
    
                private static BalanceRestClient instance;
                private IBalanceService request;
    
                private BalanceRestClient() {
                    Retrofit retrofit = new Retrofit.Builder()
                            .baseUrl("http://hovermind.com")
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(rxAdapter)
                            .build();
    
                    request = retrofit.create(IBalanceService.class);
                }
    
                public static synchronized BalanceRestClient getInstance() {
                    if (instance == null)
                        instance = new BalanceRestClient();
    
                    return instance;
                }
    
                public void getRequest(String userName, YourCustomeCallback callback) {
    
                    Call<User> call = apiService.getUser(username);
                    call.enqueue(new Callback<User>() {
    
                        @Override
                        public void onResponse(Call<User> call, Response<User> response) {
    
                            User user = response.body();
    
                            callback.onResponse(user);
    
                        }
    
                        @Override
                        public void onFailure(Call<User> call, Throwable t) {
                            // Log error here since request failed
                        }
    
                    });
                }
            }
    
    1. Create a singleton class. Its init a request only once.
    2. Create a custom callback, which will give back your response to UI.
    3. Call BalanceRestClient.getInstance.getRequest(params..) where you want to use it.
    0 讨论(0)
  • 2021-01-23 06:42

    Make an interface like this on:

    public interface BalanceListener {
    
        void onUserAvailable(User user);
    
    }
    

    In your BalanceRestClient have an instance of it. And in onResponse:

      @Override
      public void onResponse(Call<User> call, Response<User> response) {
    
          User user = response.body();  
    
          listener.onUserAvailable(user);
    
      }
    

    Make your Activity implement BalanceListner:

     public class BalanceActivity extends Activity implements BalanceListener {
                    ......
    
            @Override
            public void onUserAvailable(User user) {
                // update user views here
            }
        }
    
    0 讨论(0)
提交回复
热议问题