Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use retrofit with a singleton?

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?

like image 732
user1796624 Avatar asked Apr 14 '16 16:04

user1796624


People also ask

Should Retrofit be a Singleton?

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 .

Is retrofit thread safe?

Judging from this answer I'd say, no.


2 Answers

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

like image 175
jakubbialkowski Avatar answered Oct 18 '22 19:10

jakubbialkowski


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

like image 29
GreyBeardedGeek Avatar answered Oct 18 '22 17:10

GreyBeardedGeek