user1796624 user1796624 - 10 months ago 85
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 ;)

RestAdapter restAdapter = new RestAdapter.Builder()
.setConverter(new GsonConverter(gson))
.setRequestInterceptor(new SessionRequestInterceptor())

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

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 Source

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).