I'm new to retrofit and want to know what's the best practice.
Here is some abstracted code that I found online:
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.
What's the best practice? Please keep in mind that I don't want to use dependency injection, I just want to understand how best to use retrofit.
How would some of you make this call?
2 Answers. Show activity on this post. You should make RestClient as singleton in any way that you like (enum, standard getInstance() or even double check ). Keeping them as singleton will increase performance, because you will not create each time costful objects like Gson , RestAdapter and ApiService .
Judging from this answer I'd say, no.
You should make RestClient
as singleton in any way that you like (enum, standard getInstance()
or even double check
).
Keeping them as singleton will increase performance, because you will not create each time costful objects like Gson
, RestAdapter
and ApiService
.
Edit: Max requests which could be handled at the same time by Retrofit is dependent on HttpClient configuration.
When using with OkHttp
default value is 64 (it is defined in Dispatcher
).
However it can be manipulated via setMaxRequests()
, keep in mind to not spawn too many threads (it can lead to OutOfMemory).
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With