Sandeep Sankla
Sandeep Sankla

Reputation: 1260

Exxplicitly syncing of local Firestore cache with Server

I am using Firestore DB, need to know is there any way to explicitly sync the data to the server from the local cache. Because I can see some time document snapshot. metadata.HasPendingWrite() is true.

Is there any way to get a pending Document Count or getting those documents from a pending document?

Upvotes: 0

Views: 338

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138834

According to the official documentation regarding Firestore offline persistence:

For Android and iOS, offline persistence is enabled by default.

This means that while offline, pending writes that have not yet been synced to the server are held in a queue in the local cache. This also means that:

metadata.hasPendingWrite() 

Will return "true", because all those writes are in a "pending" state. As soon as the device regains connectivity, everything from the queue will be synced with the Firebase servers and vice versa.

I am using Firestore DB, need to know is there any way to explicitly sync the data to the server from the local cache.

There is no need to do something explicitly. Firestore will do this automatically for you.

Is there any way to get a pending Document Count or getting those documents from pending Documents?

Yes, you can create a query, and count only the documents that are in a "pending" state. Basically, the documents that not yet synced with the Firebase servers.

Edit:

Assuming you have a collection of products and you want to get the count of documents in a "pending" state, please use the following lines of code:

productsRef.addSnapshotListener(new EventListener<QuerySnapshot>() {
    @Override
    public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException e) {
        if (e != null) {
            Log.w(TAG, "Listen failed.", e);
            return;
        }

        int count = 0;
        for (QueryDocumentSnapshot doc : value) {
            if (doc.getMetadata().hasPendingWrites()) {
                count++;
            }
        }
        Log.d(TAG, "count: "+ count);
    }
});

Upvotes: 1

Related Questions