Wait for Firestore queries to complete

非 Y 不嫁゛ 提交于 2021-02-16 15:28:28

问题


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;

}


回答1:


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

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



来源:https://stackoverflow.com/questions/56402128/wait-for-firestore-queries-to-complete

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