There is a delay on updating a Timestamp field compared to any other field

Viewed 98

I am streaming a document using StreamBuilder and it prints HELLO every time there is a change to the document.

StreamBuilder(
            stream: FirebaseFirestore.instance.collection('collection').doc('ABC').snapshots();,
            builder: (_context, snapshot) {
              if (!snapshot.hasData) return CircularProgressIndicator();
              print('HELLO');
              return Container();
            }

Now when I update the document by

onTap: () => 
        FirebaseFirestore.instance.collection('collection').doc('ABC').update({'fruit':'apple','color':'golden'}),

the word HELLO gets printed once which is supposed to... However when I update a Timestamp field and a regular field

onTap: () => 
    FirebaseFirestore.instance.collection('collection').doc('ABC').update({'fruit':'apple','time': FieldValue.serverTimestamp()}),

the word HELLO gets printed twice in the console.. which is not supposed to..

1 Answers

This is actually the intended behaviour.

Here are the steps when you set a Firestore document field to the serverTimestamp FieldValue.

  1. The listener fires the first time with the initial contents of the document. (If the document doesn’t already exist, the snapshot will indicate that it’s empty.) This is expected; no problems here.

  2. Then, when set() is called, the listener fires immediately, before the write hits the server. The SDK doesn’t deliver the token value to the listener. Instead, it simply delivers null (for now), because the final value isn’t known (yet).

  3. Then, after the document gets synchronized with the server, the listener fires again with the new timestamp value determined by Firestore.

Source: https://medium.com/firebase-developers/the-secrets-of-firestore-fieldvalue-servertimestamp-revealed-29dd7a38a82b

So the reason "HELLO" gets printed twice is that the snapshot data is returned at first after the fields are updated with the server timestamp as null, then the snapshot data is returned after the server timestamp is updated.

Related