我正在尝试使用Firestore来为集合设置实时侦听器。每当在集合中添加,修改或删除文档时,我都希望调用该侦听器。我的代码当前适用于一个集合,但是当我在更大的集合上尝试相同的代码时,它失败并显示以下错误:
侦听失败:com.google.cloud.firestore.FirestoreException:后端已结束侦听流:数据存储操作超时,或数据暂时不可用。
这是我实际的侦听器代码:
/**
* Sets up a listener at the given collection reference. When changes are made in this collection, it writes a flat
* text file for import into backend.
* @param collectionReference The Collection Reference that we want to listen to for changes.
*/
public static void listenToCollection(CollectionReference collectionReference) {
AtomicBoolean initialUpdate = new AtomicBoolean(true);
System.out.println("Initializing listener for: " + collectionReference.getId());
collectionReference.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirestoreException e) {
// Error Handling
if (e != null) {
System.err.println("Listen failed: " + e);
return;
}
// If this is the first time this function is called, it's simply reading everything in the collection
// We don't care about the initial value, only the updates, so we simply ignore the first call
if (initialUpdate.get()) {
initialUpdate.set(false);
System.out.println("Initial update complete...\nListener active for " + collectionReference.getId() + "...");
return;
}
// A document has changed, propagate this back to backend by writing text file.
for (DocumentChange dc : queryDocumentSnapshots.getDocumentChanges()) {
String docId = dc.getDocument().getId();
Map<String, Object> docData = dc.getDocument().getData();
String folderPath = createFolderPath(collectionReference, docId, docData);
switch (dc.getType()) {
case ADDED:
System.out.println("Document Created: " + docId);
writeMapToFile(docData, folderPath, "CREATE");
break;
case MODIFIED:
System.out.println("Document Updated: " + docId);
writeMapToFile(docData, folderPath, "UPDATE");
break;
case REMOVED:
System.out.println("Document Deleted: " + docId);
writeMapToFile(docData, folderPath, "DELETE");
break;
default:
break;
}
}
}
});
}
在我看来,该收藏太大,并且该收藏的初始下载正在超时。我可以使用某种方法来实时获取此收藏集的更新吗?
最佳答案
我与Firebase小组取得了联系,他们目前正在就此问题与我联系。同时,我可以通过基于Last Updated timestamp属性查询集合来减小侦听器的大小。我只查看最近更新的文档,并且只要进行更改,我的应用程序就会更改此属性。