Home > front end >  Listen for documents just when actually added to collection - swift
Listen for documents just when actually added to collection - swift

Time:11-11

I have a collection on Firestore and I listen for changes like this:

    func createMatchesListener(){

    let db = Firestore.firestore()
    guard let currentUid = Auth.auth().currentUser?.uid else { return }
    
    matchesListener = db.collection("Matches").document(currentUid).collection("Matches").addSnapshotListener({ snapshot, error in
        if let error = error{
            print(error.localizedDescription)
            return
        }
        
        snapshot?.documentChanges.forEach({ change in
            if change.type == .added{
                
               // do things
            }
        })
    })
}

I only want to listen for documents that are actually added to that collection. In fact, the problem is that whenever I invoke this function I receive all the documents of the collection as added documents and then I also receive documents added later.

How can I listen just for actually added documents? Searching online I didn't find any solution to this issue.

CodePudding user response:

You can store an array with the ID of the documents that you already have stored in the device. That way, all that you need to do before doing things is checking that document's id is not in your array

CodePudding user response:

There's no way of preventing Firestore from returning the initial snapshot of documents when a document listener is added, so just use a boolean to keep track of the initial snapshot and ignore it.

var listenerDidInit = false

func createMatchesListener(){
    let db = Firestore.firestore()
    guard let currentUid = Auth.auth().currentUser?.uid else { return }
    
    matchesListener = db.collection("Matches").document(currentUid).collection("Matches").addSnapshotListener({ snapshot, error in
        if let error = error{
            print(error.localizedDescription)
            return
        }
        
        if listenerDidInit {
            snapshot?.documentChanges.forEach({ change in
                if change.type == .added{
                    // do things
                }
            })
        } else {
            listenerDidInit = true
        }
    })
}
  • Related