Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to reuse builder code for retrofit

Tags:

I am using Retrofit and in every task I have to do something like this:

public class MyTask extends AsyncTask<String, String, String> {      private void someMethod() {         final RestAdapter restAdapter = new RestAdapter.Builder()             .setServer("http://10.0.2.2:8080")             .build();         final MyTaskService apiManager = restAdapter.create(MyTaskService.class);     }      // ...  } 

What is a good way to make this code DRY?

like image 216
birdy Avatar asked Dec 14 '13 02:12

birdy


2 Answers

Both the RestAdapter and the generated instance of your services (MyTaskService in this case) are extremely expensive objects and should be used as singletons.

This means that you should only ever call restAdapter.create once and re-use the same instance of MyTaskService every time you need to interact with.

I cannot stress this enough.

You can use the regular singleton pattern in order to ensure that there only is ever a single instance of these objects that you use everywhere. A dependency injection framework would also be something that could be used to manage these instances but would be a bit overkill if you are not already utilizing it.

like image 51
Jake Wharton Avatar answered Sep 23 '22 12:09

Jake Wharton


As Jake said, you should use the singleton pattern in order to ensure the same instance is always used.

Here's an example:

public class ApiManager {      public interface GitHubService {          @GET("/users/{user}/repos")         List<Repo> listRepos(@Path("user") String user);      }      private static final String API_URL = "https://api.github.com";      private static final RestAdapter REST_ADAPTER = new RestAdapter.Builder()         .setEndpoint(API_URL)         .setLogLevel(LogLevel.FULL)         .build();      private static final GitHubService GIT_HUB_SERVICE = REST_ADAPTER.create(GitHubService.class);      public static GitHubService getService() {         return GIT_HUB_SERVICE;     } } 

You can use the service in this example like so:

ApiManager.getService().listRepos(...); 
like image 28
Gautam Avatar answered Sep 22 '22 12:09

Gautam