Vasile
Vasile

Reputation: 79

Which to use, addSnapshotListener() or getDocuments()

I'm a little bit confused about addSnapshotListener and getDocuments. As I read in the firebase docs, getDocuments() is retrieving data once and addSnapshotListener is retrieving in real-time.

What I want to ask.

If I'm using getDocuments, and im changing some documents in the Firestore , it will not make the change in the app ? But if im using addSnapshotListener it will ?

I'm making an delivery app, which is the best to use to store pictures of food , descriptions etc.

This is what im using to retrieve labels and pictures from my app :

db.collection("labels").getDocuments { (snapshot, error) in
            if let error = error {
                print(error)
                return
            } else {
                for document in snapshot!.documents {
                    let data = document.data()
                    let newEntry = Labels(
                        firstLabel: data["firstLabel"] as! String,
                        secondLabel: data["secondLabel"] as! String,
                        photoKey: data["photoKey"] as! String
                    )
                    
                        
                        
                        
                    self.labels
                        .append(newEntry)
                }
            }
            DispatchQueue.main.async {
                self.tableViewTest.reloadData()
            }

Upvotes: 2

Views: 868

Answers (1)

jnpdx
jnpdx

Reputation: 52347

getDocuments will return results one time, with the current Firestore data.

addSnapshotListener will return an initial result set (same as getDocuments) and get called any time that data changes.

If your data is modified in Firestore and you've used getDocuments, your app will not be notified of those changes. For example, in your delivery app, perhaps the item goes out-of-stock while the user is using it. Or, the price gets changed, the user is logged in from another device, etc -- many possibilities for why the data might change. By using a snapshot listener, you'd get notified if any of these changes happen.

However, if you're relatively confident you don't need updates to the data (like getting a user's address from the database, for example), you could opt to just use getDocuments.

Upvotes: 5

Related Questions