等待Firestore查询完成 [英] Wait for Firestore queries to complete

查看:48
本文介绍了等待Firestore查询完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试在Firestore中运行多个查询,并希望在执行下一个代码之前等待它们全部完成.我已经阅读了几种可能的方法,但是还没有找到一个很好的Android示例.

I am currently trying to run multiple queries in firestore and want to wait for them to all complete before executing the next code. I've read up on several possible avenues but I have yet to find a good Android example.

public HashMap<String,Boolean> multipleQueries(String collection, String field, final ArrayList<String> criteria) {

HashMap<String,Boolean> resultMap = new HashMap<>();

for (int i = 0; i < criteria.size(); i++){
    final int index = i;
    db.collection(collection).whereEqualTo(field,criteria.get(i)).limit(1)
    .get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {

    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
    if(task.isSuccessful()) {
         if(task.getResult().size() != 0 ){
           resultMap.put(criteria.get(index),true);
         } else {
             resultMap.put(criteria.get(index),false);
          }
    } else {
        resultMap.put(criteria.get(index),false);

    }

    }

     });
   }
   return resultMap;

}

推荐答案

由于 get()返回 Task ,因此可以使用

Since get() returns a Task, you can use Tasks.whenAll(...).

但是您将无法从此函数返回 List ,因为所有数据都是异步加载的.最好的办法是从 Task.whenAll(...)返回结果,它本身就是一个 Task .请参阅道格·史蒂文森(Doug Stevenson)关于成为任务管理员的精彩文章: https://firebase.googleblog.com/2016/10/become-a-firebase-taskmaster-part-4.html

But you won't be able to return a List from this function, since all data is asynchronously loaded. The best you can do is return the result from Task.whenAll(...), which is itself a Task. See Doug Stevenson's great article on becoming a task master: https://firebase.googleblog.com/2016/10/become-a-firebase-taskmaster-part-4.html

这篇关于等待Firestore查询完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆