How To Get Async Call To Return Response To Main Thread, Using Okhttp?
I'm trying to make a program for Android, and I'm using okhttp for json-calls. I really want to return my response to the outside of the thread I'm creating. I need to create the t
Solution 1:
Common way to get results from asynchronous world to synchronous (thread-based) is to use Futures. Many libraries implement such an interface, e.g. Guava. Standard java has implementation named CompletableFuture. It uses methods with different names and signatures, but an adapter can be easily implemented:
classCallbackFutureextendsCompletableFuture<Response> implementsCallback {
publicvoidonResponse(Call call, Response response) {
super.complete(response);
}
publicvoidonFailure(Call call, IOException e){
super.completeExceptionally(e);
}
}
Then you can use it as follows:
CallbackFuture future = newCallbackFuture();
client.newCall(request).enqueue(future);
Response response = future.get();
Having the Response
, you can extract responseString
the same way as you did it in the your first variant.
Post a Comment for "How To Get Async Call To Return Response To Main Thread, Using Okhttp?"