Wait for all requests in Android Volley

2019-04-13 10:31发布

I'm using Volley to connect to my REST API in my Android application and for some activities, I want to take some action only after all my requests have finished. In JavaScript, for those familiar with promises like in AngularJS, I would do:

$q.all([
    resourceA.get(),
    resourceB.get(),
    resourceC.get()
])
.then(function (responses) {
    // do something with my responses
})

How can I do something like this with Volley? I know I could have the ResponseListener callbacks check against some integer that counts the requests that are pending, but this seems like a hack. Is there a simpler way to do this?

1条回答
一夜七次
2楼-- · 2019-04-13 10:42

You can use CountDownLatch.

It's a special object that blocks the current thread until it's own internal count goes to 0.

As it is blocking the current thread, you have to execute it in a separate thread (or in a service if you are sending your Volley Request from a service).

Implementation example :

this.mRequestCount = 0;
performFirstVolleyRequest(); // this method does mRequestCount++;
performSecondVolleyRequest(); // this one too ...
performThirdVolleyRequest(); // guess what ?!! This one too
// this.mRequestCount = 3. You have 3 running request.


this.mCountDownLatch requestCountDown = new CountDownLatch(mRequestCount);
final Handler mainThreadHandler = new Handler(Looper.getMainLooper());
new Thread(new Runnable() {

    @Override
    public void run() {
        requestCountDown.await();
        mainThreadHandler.post(new Runnable() {
           doSomethingWithAllTheResults();
        });
    }
}).start();

...

private static class FirstVolleyRequestListener extends Response.Listener() {

    public void onResponse(Data yourData) {
        // save your data in the activity for futur use
        mFirstRequestData = yourData;
        mCountDownLatch.countDown();
    }
}

// You have other Volley Listeners like this one
查看更多
登录 后发表回答