Wait for all requests in Android Volley

柔情痞子 提交于 2020-01-01 18:53:47

问题


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:


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


来源:https://stackoverflow.com/questions/27108391/wait-for-all-requests-in-android-volley

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