java 改造:如何等待响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35639232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrofit: How to wait for response
提问by neustart47
I have AsyncTask and the doInBackground method inside which, I sending POST request using Retrofit. My code looks like:
我有 AsyncTask 和 doInBackground 方法,我在其中使用 Retrofit 发送 POST 请求。我的代码看起来像:
//method of AsyncTask
protected Boolean doInBackground(Void... params) {
Retrofit restAdapter = new Retrofit.Builder()
.baseUrl(Constants.ROOT_API_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
IConstructSecureAPI service = restAdapter.create(IConstructSecureAPI.class);
//request
Call<JsonElement> result = service.getToken("TestUser", "pass", "password");
result.enqueue(new Callback<JsonElement>() {
@Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
}
@Override
public void onFailure(Call<JsonElement> call, Throwable t) {
}
});
return true;
}
The problem is: Retrofit sending request asynchronously and while it, the doInBackground method returning the value. So I need to send a request in the same thread with all executions in the sequence. One by one. And returning from doInBackground occurs after the request finished. How can I send a request in the same thread using Retrofit?
问题是:改造异步发送请求,同时 doInBackground 方法返回值。所以我需要在同一个线程中发送一个请求,并按顺序执行所有操作。逐个。并且在请求完成后从 doInBackground 返回。如何使用 Retrofit 在同一线程中发送请求?
回答by Bryan Herbst
回答by Emma
"Retrofit sending request asynchronously" which as @Tanis.7x mentioned, enqueue() is doing the asynchronous, so what could be a reason to put in AsyncTask ? (async in async ?)
正如@Tanis.7x 提到的“异步改造发送请求”, enqueue() 正在执行异步操作,那么放入 AsyncTask 的原因是什么?(异步中的异步?)
You can simply put all retrofit code out from AsyncTask and onResponse
is the callback that is waiting for your request call to be back, so you can do any UI update inside of this callback.
您可以简单地从 AsyncTask 中取出所有改造代码,并且onResponse
是等待您的请求调用返回的回调,因此您可以在此回调中执行任何 UI 更新。