Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Firestore have listener that is the equivalent of Firebase's childAdded (using swift)?

I think i'm right and Firebase had a childAdded method and a listener which meant that all the data was loaded the first time around and then the listener would observe for each time a new piece of data was added/modified/etc.

Using Firestore I call the following on the database when my app loads:

   func loadMessageRequests()
        {

            defaultStore?.collection("requests").getDocuments() { (querySnapshot, err) in
                if let err = err {
                    print("Error getting documents: \(err)")
                } else
etc.

And I populate a dictionary with the requests.

But I also want to listen for any changes to the db and if any requests are added, etc. and at the moment I've got a separate listener in a controller doing the listening

 let listener = model.defaultStore?.collection("requests")
            .addSnapshotListener { querySnapshot, error in 

And I was just wondering whether there was an equivalent for childAdded where I can have a listener on the db while also having loaded all the data initially.

Thanks.

like image 525
Mike Avatar asked Nov 26 '17 08:11

Mike


1 Answers

In Firestore the API is slightly different, but the information and functionality you're looking for is still available.

There is only one type of listener in Firestore and you attach it by calling addSnapshotListener. This fires immediately for the initial value and from then on for any changes to the data.

When the snapshot listener fires, you get a QuerySnapshot that contains the updated data and information about the changes to that data. The changes are encapsulated in a documentChanges array. Each individual DocumentChange has a type that indicates whether the document was added, removed, or modified.

An easy example of how this works can be found in FirebaseUI for Android. The FirebaseUI iOS library listens to the same protocol, but somehow I find it much harder to parse what it's doing.

like image 134
Frank van Puffelen Avatar answered Sep 21 '22 02:09

Frank van Puffelen