如果插入状态为“成功”的文档,
addSnapshotListener
回调会返回所有状态为“成功”的文档(新的和现有的)还是仅返回新插入的状态为“成功”的文档?
private func monitorNoteChanges() {
guard let uid = Auth.auth().currentUser?.uid else { return }
self.stopMonitoring()
let db = FirestoreUtils.firestore()
// Reference to the notes subcollection for the specific user
let notesRef = db.collection("users").document(uid).collection("notes")
let statusValues = [
Status.success.rawValue
]
// Query to listen for changes to documents where status matches the specified value
let query = notesRef.whereField("status", in: statusValues).whereField("trashed", isEqualTo: false)
// Attach a listener and store the ListenerRegistration
let listener = query.addSnapshotListener { [weak self] (querySnapshot, error) in
guard let self = self else { return }
guard let documents = querySnapshot?.documents else {
print("No documents or an error occurred: \(error?.localizedDescription ?? "Unknown error")")
return
}
// TODO: documents
}
self.listener = listener
}
最初,我以为监听器只会返回新插入的文档。
但是,我注意到每当插入新文档时,都会返回新文档和所有现有的匹配文档。
这种行为正确且有保证吗?
由于您循环
querySnapshot?.documents
,您将始终获得所有匹配的文档。
如果您想处理所做的特定更改,请循环
querySnapshot?.documentChanges
并检查其中每个差异的 type
。
有关此内容的更多信息,请参阅有关“查看快照之间的更改”的文档。那里的代码示例:
db.collection("cities").whereField("state", isEqualTo: "CA")
.addSnapshotListener { querySnapshot, error in
guard let snapshot = querySnapshot else {
print("Error fetching snapshots: \(error!)")
return
}
snapshot.documentChanges.forEach { diff in
if (diff.type == .added) {
print("New city: \(diff.document.data())")
}
if (diff.type == .modified) {
print("Modified city: \(diff.document.data())")
}
if (diff.type == .removed) {
print("Removed city: \(diff.document.data())")
}
}
}
因此,如果您添加了一份新文档,
snapshot.documentChanges
将只有一个带有
diff.type == .added
的条目。