0

I am trying to listen for newly added documents in firestore. But when i listen with snapshotListener all the available documents are downloaded, which i dont want. I only need the documents that are created after snapshotListener started listening

ismailfarisi
  • 249
  • 1
  • 2
  • 8

2 Answers2

0

Docs link https://firebase.google.com/docs/firestore/query-data/listen

for example if you wanna listen to any new comment in a post and only update that, this is how the code would look

db
.collection('posts')
.doc(postId)
.collection('comments')
.orderBy('timestamp', 'desc')
.onSnapshot((snapshot) => {
          setComments(snapshot.docs.map((doc) => doc.data()));
        }

here onSnapshot is the listener you need, the above example says go to collection post with postID, then comments collection and order by it timestamp.

0
Firebase.firestore.collection("collectoin")
                .addSnapshotListener { snapshots, e ->
                    if (e != null) {
                        return@addSnapshotListener
                    }
                    for (dc in snapshots!!.documentChanges) {
                        when (dc.type) {
                            DocumentChange.Type.ADDED -> Log.d(
                                TAG,
                                "New added: ${dc.document.data}"
                            )
                            DocumentChange.Type.MODIFIED -> Log.d(
                                TAG,
                                "Modified: ${dc.document.data}"
                            )
                            DocumentChange.Type.REMOVED -> Log.d(
                                TAG,
                                "Removed: ${dc.document.data}"
                            )
                        }
                    }
                }

The first query snapshot contains added events for all existing documents that match the query. This is because you're getting a set of changes that bring your query snapshot current with the initial state of the query. This allows you, for instance, to directly populate your UI from the changes you receive in the first query snapshot, without needing to add special logic for handling the initial state see reference here and

Abubakar
  • 336
  • 4
  • 13
  • but the problem is i only need the documents thats added after starting listening. otherwise the whole app logic will not work – ismailfarisi Aug 12 '20 at 12:03