Reputation: 1539
I am building a Retrofit client. As part of this client, I am also building an OkHttpClient within it. Below is the code I am speaking of:
public static final String BASE_URL = "https://api.darksky.net/forecast/<secret-key>/";
public static final OkHttpClient.Builder httpClient = new OkHttpClient.Builder().dispatcher()
private static Retrofit retrofit = null;
public static DarkSkyEndpoints getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
}
DarkSkyEndpoints endpoints = retrofit.create(DarkSkyEndpoints.class);
return endpoints;
}
I want to build an OkHttpClient that only allows 1 concurrent thread at a time.
I know there is a method called dispatcher() that can be chained next to an OkHttpClient.Builder() as shown above.
I know that the Dispatcher class has a method setMaxRequests() that accomplishes exactly what I want to do.
How do I set the maximum number of concurrent threads when building an OkHttpClient for Retrofit?
Upvotes: 5
Views: 1212
Reputation: 1891
You need create instance of Dispatcher
class and pass it to dispatcher()
method. Try something like this:
Dispatcher dispatcher = new Dispatcher();
dispatcher.setMaxRequests(MAX_REQUESTS_NUMBER);
public static final OkHttpClient httpClient = new
OkHttpClient.Builder().dispatcher(dispatcher).build();
....
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient)
.build();
Upvotes: 4