Handle SocketTimeException in Retrofit with ease in android
Hola! android world, its good to see you again this sort of post, well it is short and sweet, but definitely worth your time
Well! if you used or using retrofit in your applications, you will or already met up with Socket Time Exception error, You could definitely use try and catch but it is not the best way to handle that,
Let's understand this error
SocketTimeException- We can little bit assume with the name that this error was caused by some sort of time out, Well in this case it was caused because the server failed to respond to the API call made by the client during the specified amount of time(in seconds)
Time to tackle it
You just need to use the OkHttpClient object and pass it on to the retrofit instance
Let's look at a simple snippet
val client: OkHttpClient = OkHttpClient.Builder()
.connectTimeout(100, TimeUnit.SECONDS)
.readTimeout(100, TimeUnit.SECONDS).build()
Let's pass it on to the retrofit instance
Retrofit.Builder().baseUrl(BASE_URL!!)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
Voila! Now you have given enough time in this case 100 seconds to load the API request, you can play with the OkHttpClient parameter and use it with preferred customization
Thanks for reading