I have set a global timeout in my Retrofit adapter by doing
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setReadTimeout(20, TimeUnit.SECONDS);
okHttpClient.setConnectTimeout(20, TimeUnit.SECONDS);
retrofit = new Retrofit.Builder()
.client(okHttpClient)
.build();
Great! But I would like to set an specific timeout for certain requests E.g.
public interface MyAPI {
@GET()
Call<Void> notImportant (@Url String url);
@GET
Call<Void> veryImportant(@Url String url);
So veryImportant
calls I would like a timeout of 35 seconds but notImportant
the default
Is this possible?
My research has fallen flat.
I came across this however but not sure if it will work in Retrofit
https://github.com/square/okhttp/wiki/Recipes#per-call-configuration
Thank you for reading. Please help.
You can do that by creating overloaded method of your retrofit object factory method. It's maybe look like this.
public class RestClient {
public static final int DEFAULT_TIMEOUT = 20;
public static <S> S createService(Class<S> serviceClass) {
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
OkHttpClient client = httpClient.build();
okHttpClient.setReadTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
okHttpClient.setConnectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
.client(client)
.build();
return retrofit.create(serviceClass);
}
public static <S> S createService(Class<S> serviceClass, int timeout) {
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
OkHttpClient client = httpClient.build();
okHttpClient.setReadTimeout(timeout, TimeUnit.SECONDS);
okHttpClient.setConnectTimeout(timeout, TimeUnit.SECONDS);
Retrofit retrofit = new Retrofit.Builder().baseUrl(APIConfig.BASE_URL)
.client(client)
.build();
return retrofit.create(serviceClass);
}
}
if you want to call api with default timout, you can call it look like this.
MyAPI api = RestClient.createService(MyAPI.class);
api.notImportant();
And use the second one if you want to call api with authentication:
int timeout = 35;
MyAPI api2 = RestClient.createService(MYAPI.class, timeout);
api2.veryImportant();
Another solution is by creating different method with different OkHttpClient configuration instead of creating overloaded method. Hope this solution fix your problem.
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