Search code examples
swiftfirebasegoogle-cloud-firestorelistenersnapshot

How can i change the whereField value of shapshotListener properly in swift?


I need to change the whereField variable value in "snapshotListener" Query.

Even if I call the code listener?.remove before the change, snapshot according to the previous query criteria is restarting to listening, while i am calling the "shapshotListener" with new whereField value.

At the same time, snapshot according to the new query criteria is starting to listening also.

So ı am receiving 2 different snapshots when there is any change in the documents.

I would like to explain with code:

Step 1 (think that UserID is 111)

listener = Firestore.firestore().collection("Annotations").whereField("UserID", isEqualTo: \(UserID)).addSnapshotListener { (snapshot, error) in

        if error != nil {}else {
            if snapshot?.isEmpty == false && snapshot != nil {
                for document in snapshot!.documents {
                    if let snapshotUserID = document.get("UserID") as? String {

                        print("snapshotUserID: \(snapshotUserID)")
                        print("UserID: \(UserID)")
                    }
                }
            }
        }
    }

Step 2

listener?.remove

Step 3

UserID = 112

Step 4

listener = Firestore.firestore().collection("Annotations").whereField("UserID", isEqualTo: \(UserID)).addSnapshotListener { (snapshot, error) in

        if error != nil {}else {
            if snapshot?.isEmpty == false && snapshot != nil {
                for document in snapshot!.documents {
                    if let snapshotUserID = document.get("UserID") as? String {

                        print("snapshotUserID: \(snapshotUserID)")
                        print("UserID: \(UserID)")
                    }
                }
            }
        }
    }

Now, I have 2 shapshotListeners for both of UserID documents.

Think that if there will be any change in the document with UserID 111, in the console, it will write like this;

snapshotUserID: 111

UserID: 112

How can I change the query parameter of shapshotListener properly?


Solution

  • It's not possible to change a query while a listener is attached and receiving results. What you're doing right now is the best you can do - remove the listener, build a new query, and add a new listener to that query. If you don't want to handle any duplicated data from the new query, you will to figure out how to skip the snapshots you don't want to process.