Firestore - use cache before updating online content

I start with Firestore. I read documents and tutorials about the autonomy of offline data, but I didn't quite understand that Firestore was loading the data again, even if the content was not changed. For example, if I have a query in which the results will be updated once a week, and I do not need the application to download the content again until the changes have been made, what is the best way in terms of writing code efficiently? Thanks!

+9
source share
1 answer

Do you want to use the snapshot receiver API to listen to your request: https://firebase.google.com/docs/firestore/query-data/listen#listen_to_multiple_documents_in_a_collection

Here is some JavaScript as an example:

db.collection("cities").where("state", "==", "CA") .onSnapshot(function(querySnapshot) { var cities = []; querySnapshot.forEach(function(doc) { cities.push(doc.data().name); }); console.log("Current cities in CA: ", cities.join(", ")); }); 

The first time you connect this listener, Firestore will connect to the network to download all the results in your request and provide you with a snapshot of the request, as you would expect.

If you connect the same listener a second time and use autonomous persistence, the listener will immediately start with the results from the cache. Here's how you can determine if your cache result is local or local:

 db.collection("cities").where("state", "==", "CA") .onSnapshot({ includeQueryMetadataChanges: true }, function(snapshot) { snapshot.docChanges.forEach(function(change) { if (change.type === "added") { console.log("New city: ", change.doc.data()); } var source = snapshot.metadata.fromCache ? "local cache" : "server"; console.log("Data came from " + source); }); }); 

After you get the cached result, Firestore will check on the server for any changes to your request. If so, you will get another snapshot with the changes.

If you want to be notified of changes that apply only to metadata (for example, if no documents are changed except changes to snapshot.metadata.fromCache ), you can use QueryListenOptions when QueryListenOptions : https://firebase.google.com/docs/ reference / android / COM / Google / firebase / FireStore / QueryListenOptions

+4
source

Source: https://habr.com/ru/post/1272799/


All Articles