Wait for result of Async Volley request and return it

前端 未结 2 1233
北荒
北荒 2020-12-05 16:37

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 a

相关标签:
2条回答
  • 2020-12-05 17:25

    You can achieve this using the library 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.

    0 讨论(0)
  • 2020-12-05 17:34

    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:

    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).

    0 讨论(0)
提交回复
热议问题