Java 等待 Async Volley 请求的结果并返回

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19409088/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 16:55:27  来源:igfitidea点击:

Wait for result of Async Volley request and return it

javaandroidasynchronousanonymous-functionandroid-volley

提问by chinabean

Below is a method in which I am trying to retrieve an user object by calling getSelf(). Problem is that the result is always null since the Volley request has not finished at the time of returning the result. I'm somewhat new to async processes, so I am not sure of the best way to have the method wait for the result of the API call to return the UserBean object. Can anyone give me some help?

下面是我试图通过调用 getSelf() 来检索用户对象的方法。问题是结果始终为空,因为在返回结果时 Volley 请求尚未完成。我对异步进程有点陌生,所以我不确定让方法等待 API 调用的结果返回 UserBean 对象的最佳方法。任何人都可以给我一些帮助吗?

public UserBean getSelf(String url){

    RpcJSONObject jsonRequest = new RpcJSONObject("getSelf", new JSONArray());

    JsonObjectRequest userRequest = new JsonObjectRequest(Request.Method.POST, url, jsonRequest, 
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                String result;
                try {
                    result = response.getString("result");
                    Gson gson = new Gson();
                    java.lang.reflect.Type listType = new TypeToken<UserBean>() {}.getType();

                    //HOW DO I RETURN THIS VALUE VIA THE PARENT METHOD??
                    userBean = (UserBean) gson.fromJson(result, listType);

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
               Log.e("Error:", error.toString());
               finish();
            }
        }
    );

    this.queue.add(userRequest);


    return userBean;

}   

回答by 1HaKr

You can achieve this using the library VolleyPlus https://github.com/DWorkS/VolleyPlus

您可以使用库 VolleyPlus https://github.com/DWorkS/VolleyPlus实现此目的

It has something called VolleyTickle and RequestTickle. Request is the same. It is synchronous Request and only one request at time.

它有一个叫做 VolleyTickle 和 RequestTickle 的东西。请求是一样的。它是同步请求,一次只有一个请求。

回答by Max Malysh

For those coming to this question from search & google.

对于那些从搜索和谷歌提出这个问题的人。

There is no reason to wait for an async request to finish, as it is asynchronous by design. If you want to achieve synchronous behaviour using Volley, you have to use so-called futures:

没有理由等待异步请求完成,因为它是异步设计的。如果要使用 Volley 实现同步行为,则必须使用所谓的futures

String url = "http://www.google.com/humans.txt";

RequestFuture<String> future = RequestFuture.newFuture();
StringRequest request = new StringRequest(Request.Method.GET, url, future, future)
mRequestQueue.add(request);

String result = future.get(); // this line will block

Keep in mind that you have to run blocking code in another thread, so wrap it into AsyncTask(otherwise future.get()will block forever).

请记住,您必须在另一个线程中运行阻塞代码,因此将其包装到AsyncTask(否则future.get()将永远阻塞)。