问题
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