how to wait the volley response to finish it's

2020-07-25 10:41发布

问题:

Working with intentservice to get the data of 7 Rss Feed links with using " Google Volley " in the background and use ResultReceiver to get the result , But I can't configure how to wait on the volley response to finish it's job to fire flag with ResultReceiver to display the data in the MainActivity

回答1:

You shouldn't wait for it. You have two ways to make a network request: synchronous and asynchronous. If you use synchronous, you don't wait for result because the network call is a blocking operation.

Refer this if you want to go this direction: Can I do a synchronous request with volley?

If you want to make it asynchronous, you just start a request and then use your ResultReceiver in a Response.Listener callback method once the request is finished.

Refer this for the details: https://guides.codepath.com/android/Networking-with-the-Volley-Library

If you still think you should block the current thread and wait for result, you should use CountDownLatch. Create a background thread (you cannot block UI thread in android unless it's a separate process), init your latch with count 1 and call await() method. This will block your background thread till the count is 0. Once your background task is finished you call countDown() which will unblock your background thread and you will be able to perform your action then.



回答2:

This question was answered in the official Volley Google Group.

Wrap the request in a RequestFuture to make a blocking call using RequestFuture#newFuture(...);

You can find sample code in the Volley source code:

RequestFuture<SONObject> future = RequestFuture.newFuture();
MyRequest request = new MyRequest(URL, future, future);

// If you want to be able to cancel the request:
future.setRequest(requestQueue.add(request));

// Otherwise:
requestQueue.add(request);

try {
  JSONObject response = future.get();
  // do something with response
} catch (InterruptedException e) {
  // handle the error
} catch (ExecutionException e) {
  // handle the error
}

Be sure to use a timeout in future.get(...) or else your thread will lock.