我尝试使用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;
}
}
}
});
}
在我看来,该集合太大,并且该集合的初始下载超时。我是否可以使用某种工作来实时获取此集合的更新?
答案 0 :(得分:0)
我联系了Firebase团队,他们目前正在回答这个问题。与此同时,我可以通过基于 Last Updated timestamp属性查询集合来减小侦听器的大小。我只查看了最近更新过的文档,并且只要进行了更改,我的应用就会更改此属性。