I want to request to a url using okhttp in another thread (like IO thread) and get Response in the Android main thread, But I don\'t know how to create an
I came late to the discussion but, if for some reason the code need to stream the response body, then defer or fromCallable won't do it. Instead one can employ the using operator.
Single.using(() -> okHttpClient.newCall(okRequest).execute(), // 1
response -> { // 2
...
return Single.just((Consumer) fileOutput -> {
try (InputStream upstreamResponseStream = response.body().byteStream();
OutputStream fileOutput = responseBodyOutput) {
ByteStreams.copy(upstreamResponseStream, output);
}
});
},
Response::close, // 3
false) // 4
.subscribeOn(Schedulers.io()) // 5
.subscribe(copier -> copier.accept(...), // 6
throwable -> ...); // 7
Single.just(...)defer one could have used the try-with-resources style.eager toggle to false to make the disposer called after the terminal event, i.e. after the subscription consumer has been executed.eager set to false, the code will raise an IOException with reason 'closed' because the response will be already closed before entering this lambda.onError lambda should handle exceptions, especially the IOException that cannot be anymore caught with the using operator as it was possible with a try/catch with defer.