Tasks.whenAllSuccess是否保证传入任务的结果顺序?(Cloud Firestore场景)
Great questions! Let's break them down clearly, based on Firebase's documented behavior and common real-world usage:
1. Does Tasks.whenAllSuccess guarantee the order of input tasks?
Absolutely yes. This is a deliberate, contract-guaranteed behavior of the Firebase Tasks API. When you pass multiple tasks to Tasks.whenAllSuccess(), the resulting List of results will always match the exact order of the tasks you passed in—regardless of the order in which individual tasks finish executing.
For example, if you run:
Task<DocumentSnapshot> taskA = firestore.collection("items").document("item1").get(); Task<DocumentSnapshot> taskB = firestore.collection("items").document("item2").get(); Task<List<Object>> combinedTask = Tasks.whenAllSuccess(taskA, taskB);
Even if taskB finishes milliseconds before taskA, the resulting list will have taskA's result at index 0 and taskB's result at index 1. This consistency is reliable and not a coincidence.
2. Will merged Firestore query tasks preserve their result order?
Yes—directly building on the behavior we just covered for Tasks.whenAllSuccess(). Here's how it applies to your specific use case:
- When you pass your two pre-sorted Firestore query tasks (say, first the
whereLessThanquery, then thewhereGreaterThanquery) toTasks.whenAllSuccess(), the combined task's success listener will receive a list where:- Index 0 holds the fully sorted result set from your
whereLessThanquery (exactly as it would return if run alone) - Index 1 holds the fully sorted result set from your
whereGreaterThanquery (unchanged from its standalone output)
- Index 0 holds the fully sorted result set from your
- The variable execution speed of individual queries doesn't impact this order—
Tasks.whenAllSuccess()waits for all tasks to complete, then assembles the results strictly in the order you provided the tasks.
You won't have to worry about the combined results mixing up the order of your two query sets, or altering the internal sorting of each query's results.
内容的提问来源于stack exchange,提问作者Florian Walther

