Reputation: 1697
I have a collection called Countries and inside this collection, There are 25 documents (25 countries)
When the user presses the select country button, It will take him to CountriesFragment, And when the fragment begins I will fetch the 25 countries from Firestore.
Let's suppose the user visits CountriesFragment many times and every time the user visit this fragment will cost me 25 reads, So I decided to reduce the reads costs using this way.
I created a key using SharedPreferences and I named the key lastCountriesUpdate.
I created a check if the key above is empty or not. If the value of the key was empty then that means I should fetch all countries from Firestore.
Otherwise, I'll get documents from Countries collection that has the lastUpdate value more than in the lastCountriesUpdate value.
Everything works well and I reduced the cost of reads, But the problem now is how can I know if any country was deleted from the Countries collection to remove it from the client-side?
Upvotes: 0
Views: 367
Reputation: 83163
How can I know if any country was deleted from the Countries collection to remove it from the client-side?
By default you can only know that by fetching the collection (or by fetching a specific document you know could have been deleted, but this does not correspond to your use case I think).
A possible less costly alternative approach could be to:
Countries
collection in a unique document in a specific collection (e.g. doc path like countriesLastUpdate/lastUpdate
), and;More precisely this means that:
lastUpdate
document, read the timestamp value and store it in your app.lastUpdate
document and check if the timestamp has changed. If hasn't change you use the current list saved in your app, if it has changed you do like the first time.lastUpdate
document each time there is a change in the collection. The best solution is to use a Cloud Function with the onWrite
trigger.The Cloud Function would be as simple as:
exports.countriesLastChangeUpdate = functions
.firestore
.document('countries/{docId}')
.onWrite((change, context) => {
return admin.firestore().doc('countriesLastUpdate/lastUpdate').set({lastUpdate: context.timestamp});
});
Note that there could be a tiny time lag between the country doc deletion (or creation, or change) and the completion of the Cloud Function (cold start and execution time). If you want to avoid this you could execute the country doc deletion via a Cloud Function which will update the lastUpdate
document at the same time, via a batched write.
Another variation would be to store in your app the current timestamp the first time you fetch the collection and the subsequent times check if the timestamp stored in the lastUpdate
document is after the timestamp stored in your app. You avoid the initial read of the lastUpdate
document.
Upvotes: 1