Reputation: 23
I have some Firestore requests that I try to get in a for loop
, but because Firebase queries are running Async, the results return in random order. Do you have any way to fix it? My code is below.
Thank you in advance!
for(Feed feed: feedList){
tasks.add(db.document(feed.getMarker().getPath()).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
myMarker.add(task.getResult().toObject(SavedMarker.class));
System.out.println("Marker: "+ Objects.requireNonNull(task.getResult().toObject(SavedMarker.class)).getDescription());
System.out.println("Marker: "+task.getResult().getId());
}
}));
tasks.add(db.document(feed.getUser().getPath()).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
myUser.add(task.getResult().toObject(Users.class));
}
}));
}
Tasks.whenAllSuccess(tasks).addOnCompleteListener(new OnCompleteListener<List<Object>>() {
@Override
public void onComplete(@NonNull Task<List<Object>> task) {
//Do Stuff
}
For Example:
IDX
Gives ResultX
In my feedList
I have saved 4 ids like:
ID1
ID2
ID3
ID4
But when i try to receive their results with the use of a loop
i get:
Result2
Result1
Result3
Result4
The order is usually random.
Upvotes: 1
Views: 145
Reputation: 138824
because Firebase queries are running Async, the results return in random order.
The whenAllSuccess() method from the Tasks class will always provide the documents from the tasks right into the callback in a List<Object>
. The order is the same as the order in which the tasks were added to the whenAllSuccess() method. However, if you need an order other than that, then you should either order them on the client in the way you want or create a query based on a field and order the documents as needed.
Upvotes: 1