Lis Dya
Lis Dya

Reputation: 327

How to listen for real-time updates on a list of documents in Firestore?

Currently, I'm using get(), to grab some documents from Firestore. This is my code:

val ids = getIds()
val tasks: MutableList<Task<DocumentSnapshot>> = mutableListOf()
for (id in ids) {
    tasks.add(collRef.document(id).get())
}
Tasks.whenAllSuccess<DocumentSnapshot>(tasks).addOnCompleteListener { task ->
    if (task.isSuccessful) {
        for (doc in task.result!!) {
            Log.d("TAG", doc.getString("name"))
        }
    }
}

And it works fine. getIds() returns a list of 25 Ids, so the result in the Logcat is 25 names. But this code only gets the data once, meaning that if something is added, I don't get it unless I reload the activity. I read about listen to multiple documents in a collection, but this meant to be used with a query. I tried:

Tasks.whenAllSuccess<DocumentSnapshot>(tasks).addSnapshotListener()

But Android Studio is complaining with:

Unresolved reference: addSnapshotListener

How can I listen for real-time updates for all 25 documents? Thanks

Upvotes: 1

Views: 2279

Answers (2)

Doug Stevenson
Doug Stevenson

Reputation: 317362

Tasks.whenAllSuccess() returns a new Task object that completes when all the other tasks complete. That's not going to work here at all, since listeners don't really ever "complete". If you're trying to use listeners instead of a one-time fetch with get(), you're going to need to set up a listener on each individual document reference as shown in the documentation.

for (id in ids) {
    collRef.document(id).addSnapshotListener { snapshot, e -> 
        // handle the updates here
    }
}

There is no "bulk listen" operation. Each reference needs a listener attached. You can pass the same EventListener object to each one, if you want, instead of creating a new object for each one.

Don't forget to remove the listeners when you are done.

Upvotes: 4

Rob B
Rob B

Reputation: 1289

I'm not so skilled in Kotlin but when i need to listen to a collection in Java, first i create a reference to the collection of documents and then i add SnapshotListener to the collection like this

CollectionReference ref = FirebaseFirestore.getInstance().collection("MyCollection");
    ref.addSnapshotListener(new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(@androidx.annotation.Nullable QuerySnapshot queryDocumentSnapshots, @androidx.annotation.Nullable FirebaseFirestoreException e) {
            //Here use queryDocumentSnapshot to retrieve every document data
        }
    });

Using queryDocumentSnapshots you can retrieve realtime updates to the colletion

You can also use a Query to select which documents you need to listen for

Upvotes: 0

Related Questions