Search code examples
firebasegoogle-cloud-firestoreswiftuilistenerevent-listener

Firebase Listener Called Multiple Times When Data Change SwiftUI


I have three listeners

  1. Get Visible Data to all user
  2. Get Data Between two dates
  3. Get All Data

However, When any Data change user table the Listener call automatically 4-5 times.

    func listenData() -> ListenerRegistration {
    let listener = db.collection("user")
        .whereField("FirstRow", isGreaterThanOrEqualTo: "FirstRow")
        .whereField("lastRow", isLessThanOrEqualTo: "lastRow")
        .addSnapshotListener { querySnapshot, error in
            if let error = error {
                print("listener error: \(error.localizedDescription)")
                return
            }
            if let snapshot = querySnapshot {
                print("Without For Each = Data")
                snapshot.documentChanges.forEach { diff in
                    print("For Each = Data")
                }
                print("listen Public Rides Loop Done")
            }
        }
    return listener
}

Question: How to Listener call once time when user change the data?

Can someone please explain to me How to Listener call once time only?

Any help would be greatly appreciated.

Thanks in advance.


Solution

  • Firestore's onSnapshot will always also give you the initial snapshot of the data in the database. There is no way to tell the API to skip this initial snapshot.

    If you don't need the initial data for your use-case, you will either have to ignore it in your application code, or you will have to come up with a query that only returns the documents you're interested in. That last one has been covered a few times before, so I recommend looking at the answers to these questions.

    If you want to stop listening for more updates after the first change, you can detach the listener at that point.