'How can I listen only to doc that changed in Firestore stream?

I have the following Firestore stream:

FirebaseFirestore.instance.collection("users").orderBy("timestamp", descending: true).snapshots().listen((value) async{
   // here i noticed if doc was added or updated so the stream will take action to all docs 
   in that collection
  });

For example if i write .set() to same collection like following:

.set({
 name : 'Alex'
});

and I had another doc with the field name 'jack' then I used the following in the previous stream:

stream...{
if(value['name]=='Alex'){
print('ok');
}
if(value['name]=='jack'){
print('ok'); // ok here should print 'ok' if it first snapshot , 
but it will always print 'ok' whatever the new doc equal 
my condition or not
}
}

How can I only listen to doc that newly added or updated or changed ?



Solution 1:[1]

As @Dharmaraj recommended, docChanges() method informs us of all the changes that have occurred in our database.

docChanges() method should be used on the snapshot parameter. Since that gives an array of document changes, we iterate over with a loop. If you make a console.log of the local variable of the loop, you will see that this returns each change (in the form of an object).

Example:

db.collection('recipes').onSnapshot(snapshot => {
    // console.log(snapshot.docChanges());
    snapshot.docChanges().forEach(change => {
        console.log(change);
    });
});

Do not forget that docChanges() should always be a function and never an array.

Additionally, you can add server timestamp. You can set a server timestamp in a field in your document to track when the server receives the update.

Each field receives the same server timestamp value when several timestamp fields are updated during a transaction.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jose German Perez Sanchez