我们在“模块”集合中有 2 个文档,在“模块”下名为“课程”的集合中,它们分别有 5 个和 6 个文档。当我们运行一个循环来解析集合“Modules”中的文档以使用 Firestore 从集合“Lessons”中获取文档时,外部 for 循环的运行速度比 firestore 查询本身更快,导致集合之间的值互换。我们尝试为此找到多种解决方案,使用 Tasks.whenAllSuccess() 或 Tasks.whenAllComplete(),但除了让主线程休眠 1 秒外,没有任何效果。在这种情况下,查询获取了适当的值。但是,让线程休眠肯定会冻结应用程序,这是不可取的。下面附上代码片段:
for (String moduleId : modulesDocumentIds)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
firebaseFirestore.collection("Users")
.document(userDocumentId)
.collection("Courses")
.document(courseDocumentId)
.collection("Modules")
.document(moduleId)
.collection("Lessons")
.orderBy("lesson_number",Query.Direction.ASCENDING)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
for (QueryDocumentSnapshot queryDocumentSnapshot : task.getResult())
{
// Showing Lessons
updateCourseCompletion();
}
});
}
}
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
这里,如果 moduleDocumentIds 有 2 个 String 值,没有让 Thread 休眠,因为 …