Callback if Volley RequestQueue is done with all it's tasks?

浪尽此生 提交于 2020-01-01 06:30:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!