I am using firestore along with iglistkit to display data on collection view. I am trying to understand why my snapshot listener gets called twice with the same object.
issue summary:
On Viewdidload I call the fetchUserFriends()
method and receive the documents that I am expecting from the querySnapshot but for some unknown reason, method body gets called twice, without any changes being made to the data.
The problematic code is in below:
func fetchUserFriends() {
guard let currentUserId = currentUser?.uid else { return }
db.collection("friends").whereField(FriendState.isRelationshipActive, isEqualTo: true).whereField("members", arrayContains: currentUserId).order(by: "createdAt", descending: true).addSnapshotListener { [weak self] (querySnapshot, error) in
if(error != nil) {
print("error \(String(describing: error?.localizedDescription))")
}
guard let querySnapshot = querySnapshot else { return }
for document in querySnapshot.documents {
let friendRelation = UserRelation.init(document: document)
if(self?.friendsRelations != nil) {
self?.friendsRelations?.append(friendRelation)
} else {
self?.friendsRelations = [friendRelation]
}
}
self?.adapter.reloadData(completion: nil)
}
}
Based on my debugging, what happens is that:
- fetchUserFriends() gets called
- goes through guard let querySnapshot = querySnapshot else { return } and adds the data to
friendRelations
array self?.adapter.reloadData(completion: nil)
and goes back to the 2nd step again with the same object which in this case fails due to iglistkit duplicate identifier.
Thanks for the help.