I have an RxJava chain request that should release some locks onError(), or onComplete(), so, basically, what my problem is: when I set read, connect and write timeouts to my OkHttpClient, I don't get the desired behavior. I'm using Retrofit2 and OkHttp3.6.0 Here's my simplified client:
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.readTimeout(30, TimeUnit.SECONDS)
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
OkHttpClient okHttpClient = builder.build();
Here's a simplified version of the chain request I have:
public <T extends Response> Observable<T> doSomething(Observable<T> base) {
isLocked = true;
return someApiCall()
.flatMap(apiResponse -> handleResponse(apiResponse, base)
.doOnError(throwable -> {
isLocked = false;
})
.doOnCompleted(() -> {
isLocked = false;
}));
}
handleResponse()
makes another API call and returns an Observable<Response<Something>>
but, as I've said, it sometimes fails with a HTTP FAILED: java.net.SocketException: Socket closed
and it never finishes the Observable, so, onError() or onComplete() are never called. I've tried onTerminate() also, but with no luck. When I remove the timeout settings from the OkHttlClient
, the SocketException
is actually thrown and caught which releases the isLocked
variable. I've tried wrapping the handleResponse()
return statement with a try {} catch (Exception e) {}
block, but even that doesn't catch the SocketException
when the custom timeouts are set. Any ideas?
The SocketException is an exception in Java that is thrown to indicate that an error was encountered while creating or accessing a Socket. Since the SocketException is a checked exception, it either needs to be thrown or surrounded by a try-catch block in code.
A common solution is to change your DNS server. Since the error is due to a connection issue, changing your DNS server should solve the problem.
java.net.SocketException: Connection resetThis SocketException occurs on the server-side when the client closed the socket connection before the response could be returned over the socket. For example, by quitting the browser before the response was retrieved. Connection reset simply means that a TCP RST was received.
I solved this situation in Android with the option retryOnConnectionFailure(true) set with the builder.
Given that Retrofit 2 just receive the OkHttpClient object.
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