user1796624 user1796624 - 25 days ago 21
Android Question

should I use retrofit with a singleton?

Hi Im new to retrofit and want to know whats the best practice, here is some abstracted code that Ii found online, to start with:
public class RestClient

{
private static final String BASE_URL = "your base url";
private ApiService apiService;

public RestClient()
{
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(new ItemTypeAdapterFactory()) // This is the important line ;)
.setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'")
.create();

RestAdapter restAdapter = new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL)
.setEndpoint(BASE_URL)
.setConverter(new GsonConverter(gson))
.setRequestInterceptor(new SessionRequestInterceptor())
.build();

apiService = restAdapter.create(ApiService.class);
}

public ApiService getApiService()
{
return apiService;
}
}


and lets say I want to make a api request/call with this function

RestClient restClient = new RestClient();
restClient.getApiService().getPosts();


My question is should I make a new restClient object or this should be a singleton, or the ApiService should be a singleton.
Whats the best practice? Please keep in mind that i don't wont to use dependency injection, I just want to understand how best to use retrofit.
How would some of you make this call?

Answer

The code that you have is fine. You can keep the restClient as a singleton, and then just call restClient.getApiService().getPosts(); whenever you want to get the posts again (don't create a new restClient each time).

Comments