等待在Android中凌空所有的请求 [英] Wait for all requests in Android Volley
问题描述
,我想把我所有的请求都完成后才会有所行动。在JavaScript中,对于熟悉像AngularJS,我会做的承诺:
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
})
我怎么能这样做与排球?我知道我可以有ResponseListener回调核对一些整数计算所待的请求,但是这似乎是一个黑客。有没有一种简单的方法来做到这一点?
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?
推荐答案
您可以使用的 CountDownLatch 。
这是一个特殊的对象,阻止当前线程,直到它自己内部的计数为0。
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).
实施例如:
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 = 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
这篇关于等待在Android中凌空所有的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!