Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

java - Firestore doesn't return results in requested order

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...