我正在尝试获取Cloud Firestore的实时更新。读写成功后,我在Kotlin中无法通过以下代码获得任何更新通知:
val collectionName = "users"
val docId = "alovelace"
val docRef = db.collection(collectionName).document(docId)
docRef.addSnapshotListener({ doc, e ->
System.out.println("Updated")
if (doc != null) {
if (doc.exists()) {
System.out.println("Current data: " + doc.getData())
}
else {
System.out.println("Current data: null")
}
}
else {
e!!.printStackTrace()
}
})
我可以从 docRef 中读取内容,因此这是有效的DocumentReference:
System.out.println("Get " + docRef.get().get().getData())
//print Get {last=Lovelace, born=1915, first=Bob}
我还遵循了另一个示例代码,将其包装为一个函数,并在有一个快照但仍然无效的情况下返回
fun listenToDocument(
db: Firestore,
collection: String,
document: String
): Map<String, Any>{
val future = SettableApiFuture.create<Map<String, Any>>();
// [START listen_to_document]
val docRef = db.collection(collection).document(document)
docRef.addSnapshotListener(object: EventListener<DocumentSnapshot> {
override fun onEvent(
snapshot: DocumentSnapshot?,
e: FirestoreException?
) {
if (e != null) {
System.err.println("Listen failed: " + e);
return;
}
if (snapshot != null && snapshot.exists()) {
System.out.println("Current data: " + snapshot.getData());
} else {
System.out.print("Current data: null");
}
// [START_EXCLUDE silent]
if (!future.isDone()) {
future.set(snapshot!!.getData());
}
// [END_EXCLUDE]
}
});
// [END listen_to_document]
return future.get(TIMEOUT_SECONDS, TimeUnit.SECONDS)
}
Thread( fun() {
val update = listenToDocument(db, collectionName, docId)
System.out.println(update)
}).start()
我从Web界面以及以下代码更新了文档的字段:
val writeDocRef = db.collection(collectionName).document(docId)
// Add document data with id "alovelace" using a hashmap
val data = HashMap<String, Any>()
data.put("first", "Ada")
data.put("last", "Lovelace")
data.put("born", 1815)
//asynchronously write data
val result = writeDocRef.set(data)
// result.get() blocks on response
System.out.println("Update time : " + result.get().getUpdateTime())
编写也很成功,但我只是看不到onEvent函数的任何输出,即从不调用它。我浏览了其他几个示例,包括official guides,但它们都是相似的。而且我没有看到有人对此抱怨...请帮助。