Explain Codes LogoExplain Codes Logo

How to set timeout in Retrofit library?

java
retrofit
okhttp
timeout
Anton ShumikhinbyAnton Shumikhin·Dec 3, 2024
TLDR

To set a timeout in Retrofit, customize the OkHttpClient. Leverage .readTimeout(), .writeTimeout(), and .connectTimeout(), with your desired duration and TimeUnit. Here's a swift sample:

// What's a healthy waiting time? A fresh OkHttp Client knows! OkHttpClient client = new OkHttpClient.Builder() .readTimeout(30, TimeUnit.SECONDS) // Books can't be read in 1 second .connectTimeout(30, TimeUnit.SECONDS) // Neither can we connect in the blink of an eye .build(); Retrofit retrofit = new Retrofit.Builder() .client(client) .baseUrl("http://example.com") .build();

This sets both read and connect timeouts at 30 seconds. Adjust these values per your network's mood swings.

Don't get outdated: Ensuring compatibility

Working with Retrofit and OkHttp comes with a responsibility - ensuring their versions are the best-match. Follow these computational best practices when setting timeouts:

  • Latest is greatest: Update to the newest stable releases. Here's the Retrofit 2 Upgrade Guide.

  • Play architect with a builder pattern: For setting the OkHttpClient, this increases performance and efficiency.

  • If your network requests are long-distance runners, use TimeUnit.MINUTES. Handy for a bigger minSdkVersion.

  • Test network calls post configuring timeouts. Debugger is your best friend, remember?

  • Implement onFailure callback for proper error management during network timeouts.

Call your shots: Customizing timeouts per your needs

Writing large data? Adjust timeout!

If you're sending large amount of data, adjust write timeout:

// Becomes handy especially if you're writing War and Peace over network new OkHttpClient.Builder() .writeTimeout(1, TimeUnit.MINUTES) // Gives the data enough time to pack its bags .build();

Different services, different timeouts

For finer control, set timeouts for specific Retrofit interfaces:

@POST("upload") @Streaming Call<ResponseBody> uploadImage(@Body RequestBody image);

Imagine uploading a large image. We all know, uploading a masterpiece takes time. Make that specific call an exception by extending its timeout.

Changing timeouts on-the-fly

Depending on your requirements, you might want dynamic timeout adjustments:

//Possibly the only type of mutation that isn't dangerous synchronized (retrofit) { OkHttpClient newClient = client.newBuilder() .readTimeout(newTimeout, TimeUnit.SECONDS) .build(); retrofit = retrofit.newBuilder() .client(newClient) .build(); }

Now, every new call can enjoy different timeout settings, without bothering the ongoing ones.

Adopt smart strategies: Advanced timeout management

Adapt to your user's connection

Tailor timeouts based on user's network:

// You gotta adapt to survive int timeout = isConnectedToWifi() ? 60 : 120; // Cuz data over WiFi sends chills down electricity bills okHttpClientBuilder .readTimeout(timeout, TimeUnit.SECONDS) .build();

Using coroutines with Retrofit (Kotlin)

For Kotlin lovers, handle timeouts within coroutines:

withTimeout(30000L) { // 30 seconds val response = service.fetchData() // Retrofit call }

When timeout's up, coroutine cancels the request, saving the day!