Wait for result of Async Volley request and return it

前端 未结 2 1238
北荒
北荒 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: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 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).

提交回复
热议问题