gpt4 book ai didi

android - 等待 Android Volley 中的所有请求

转载 作者:太空狗 更新时间:2023-10-29 16:36:41 26 4
gpt4 key购买 nike

我在我的 Android 应用程序中使用 Volley 连接到我的 REST API,对于某些 Activity ,我只想在我的所有请求完成后才采取一些行动。在 JavaScript 中,对于那些熟悉 AngularJS 中的 promise 的人,我会这样做:

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

我怎样才能用 Volley 做这样的事情?我知道我可以让 ResponseListener 回调检查某个整数来计算待处理的请求,但这似乎是一个 hack。有更简单的方法吗?

最佳答案

您可以使用 CountDownLatch .

这是一个特殊的对象,它会阻塞当前线程,直到它自己的内部计数变为 0。

因为它阻塞了当前线程,所以你必须在一个单独的线程中执行它(或者如果你从服务发送 Volley 请求,则在服务中执行)。

实现示例:

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

关于android - 等待 Android Volley 中的所有请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27108391/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com