【问题标题】:Wait for all requests in Android Volley等待 Android Volley 中的所有请求
【发布时间】:2014-11-24 15:33:52
【问题描述】:

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

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

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

【问题讨论】:

  • 这可能会有所帮助:code.hootsuite.com/…
  • 我会使用改造和 RxJava 而不是 Volley 来实现这一目标
  • 如果你们中的任何一个想把它放在答案中,我会接受它。 RxJava 和 Retrofit 非常适合我想做的事情。谢谢!

标签: android android-volley


【解决方案1】:

您可以使用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

【讨论】:

    猜你喜欢
    • 2013-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-04
    • 1970-01-01
    • 2023-04-05
    • 2015-04-17
    相关资源
    最近更新 更多