isakbob
isakbob

Reputation: 1539

How do I set the number of concurrent requests when building an OkHttpClient?

Background

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;
}

What I want

I want to build an OkHttpClient that only allows 1 concurrent thread at a time.

What I know

  1. I know there is a method called dispatcher() that can be chained next to an OkHttpClient.Builder() as shown above.

  2. I know that the Dispatcher class has a method setMaxRequests() that accomplishes exactly what I want to do.

What I don't know

How do I set the maximum number of concurrent threads when building an OkHttpClient for Retrofit?

Upvotes: 5

Views: 1212

Answers (1)

igor_rb
igor_rb

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

Related Questions