问题
I am using the volley networking library for android. I'am looking for a way to get notified when a bunch of requests are finished, rather than checking all the response listeners individualy (which i also do). Is there an easy way to get a callback from the queue when all tasks are done?
回答1:
Keep the requests count in a member variable and decrement everytime a request finishes, and when the counter goes to 0, you're done! I'm not aware of a callback exposed that tracks all the requests and comes back at the end.
int requestPending= 0;
for(int i=0;i<numberOfRequests;i++)
{
requestQueue.add(request);
requestPending++;
}
// For each requestQueue item finished onResponse received, do requestPending --
回答2:
I've found another way for me. It works excellent.
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
final AtomicInteger requestsCounter = new AtomicInteger(0);
for (String data: someArray) {
requestsCounter.incrementAndGet();
queue.add(new StringRequest(
Request.Method.GET,
"https://stackoverflow.com",
response -> {
...some stuff for response
},
error -> {
...catch error here
}
));
queue.addRequestFinishedListener(request -> {
requestsCounter.decrementAndGet();
if (requestsCounter.get() == 0) {
...all requests are done
}
});
}
来源:https://stackoverflow.com/questions/17719225/callback-if-volley-requestqueue-is-done-with-all-its-tasks