2

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

IBalanceService.java

public Interface IBalanceService{
  @GET("users/{username}")
  void getUser(@Path("username") String username, Callback<User> cb);
}  

BalanceRestClient.java

public class BalanceRestClient{  

  String username = "Makarov";  

  Retrofit retrofit = new Retrofit.Builder()
                               .baseUrl("http://hovermind.com")
                               .addConverterFactory(GsonConverterFactory.create())
                               .addCallAdapterFactory(rxAdapter)
                               .build();  

  IBalanceService bs = retrofit.create(IBalanceService.class);


  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();  

          // update Activity/Fragment from here  

      }

      @Override
      public void onFailure(Call<User> call, Throwable t) {
        // Log error here since request failed
      }  

   });
}

BalanceActivity.java

public BalanceActivity extends Activity{

   // BalanceRestClient will update some UI elements 
}  

How can I update UI in my Activity/fragment from onResponse()?

Additional Info:
min SDK : 19
target SDK : 23
Retrofit 2.1.0 with OkHttp and gson

MD TAREQ HASSAN
  • 1,188
  • 20
  • 46

2 Answers2

3
 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.
Robert Banyai
  • 1,329
  • 12
  • 14
  • Nice. but I am confused about singleton. what if I use BalanceRestClient multiple times in different activities. What is the problem with creating multiple instances of BalanceRestClient instead of singleton? – MD TAREQ HASSAN Dec 15 '16 at 12:24
  • Its not cost-efficient. Why would you like to create again, and again, if you did it already? – Robert Banyai Dec 15 '16 at 12:27
  • I also saw many examples where retrofit (RestAdapter) is singleton, why is that? I asked question on singleton restrofit (RestAdapter) I.e why retrofit is singleton, what is the benefit of making retrofit singleton, what if I create multiple instances of retrofit in a single activity. but unfortunately my question was marked as unclear and deleted. after that I could not ask question for few days – MD TAREQ HASSAN Dec 15 '16 at 12:31
  • @RoberBanyai I would like to use design pattern. there is a hot topic : singleton "anti-pattern" – MD TAREQ HASSAN Dec 15 '16 at 12:35
  • Because pointless to make a new istance, if you did it before. With singleton you will keep the instance in memory, and can reache whenever you want. – Robert Banyai Dec 15 '16 at 12:35
  • I got your point but instead of keeping it in memory all the time if I create instances when needed and destroy the object (I.e. balanceRestClient = null) when I am done withth it, would it be better in terms of performance? – MD TAREQ HASSAN Dec 15 '16 at 15:26
  • No, it would not. Because whenever you make a new instance allocate memory, and threads. With singleton you have to do only once. – Robert Banyai Dec 15 '16 at 15:30
1

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
        }
    }
Todor Kostov
  • 1,789
  • 1
  • 13
  • 20
  • I was also thinking about similar approach. Regarding design pattern, can you give some hint about which design pattern would be best in terms of performance. Last project I used my own library + Factory design pattern. – MD TAREQ HASSAN Dec 15 '16 at 12:20
  • @HassanMakarov I believe there is no such thing as best design pattern for optimal performance. You can use MVP / MVC patterns and still write sloppy and slow code. On the other hand, you can use no patterns and have great performance. The performance depends on 100000 things. But if you want to keep your code clean, well structured, easily scalable and to find bugs relatively easily, then use some of the patterns mentioned above. I prefer MVP. You can combine them with Singleton / Factory / Builder / etc. patterns (that depends on your current needs). – Todor Kostov Dec 15 '16 at 12:27