Firestore - 使用缓存直到在线内容更新 [英] Firestore - Using cache until online content updates
问题描述
我从 Firestore 开始.我已经阅读了有关离线数据持久性的文档和教程,但我不太清楚 Firestore 是否会再次下载数据,即使内容没有被修改.例如,如果我有一个查询,结果将每周更新一次,并且在进行更改之前我不需要应用程序再次下载内容,那么就编写代码的效率而言,最好的方法是什么?谢谢!
I am starting with Firestore. I've read docs and tutorials about the offline data persistence but I have not really clear if Firestore downloads data again even if the content hasn't been modified. For example, if I have a query where the results will be updated once a week and I don't need that the app download the content again until the changes were made, what is the best way in terms of efficiency to write the code? Thanks!
推荐答案
您想使用快照监听器"API 来监听您的查询:https://firebase.google.com/docs/firestore/query-data/listen#listen_to_multiple_documents_in_a_collection
You want to use the "snapshot listener" API to listen to your query: https://firebase.google.com/docs/firestore/query-data/listen#listen_to_multiple_documents_in_a_collection
以下是一些 JavaScript 示例:
Here's 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(", "));
});
第一次附加此侦听器时,Firestore 将访问网络以将所有结果下载到您的查询中,并如您所愿为您提供查询快照.
The first time you attach this listener Firestore will access the network to download all of the results to your query and provide you with a query snapshot, as you'd expect.
如果您第二次附加同一个侦听器并且使用离线持久性,则侦听器将立即使用缓存中的结果被触发.以下是检测结果是来自缓存还是来自本地的方法:
If you attach the same listener a second time and you're using offline persistence, the listener will be fired immediately with the results from the cache. Here's how you can detect if your result is from cache 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);
});
});
在您获得缓存结果后,Firestore 将与服务器核对以查看您的查询结果是否有任何更改.如果是,您将获得另一个包含更改的快照.
After you get the cached result, Firestore will check with the server to see if there are any changes to your query result. If yes you will get another snapshot with the changes.
如果您想收到仅涉及元数据的更改通知(例如,如果没有文档更改但snapshot.metadata.fromCache
更改),您可以在发布时使用 QueryListenOptions
您的查询:https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/QueryListenOptions
If you want to be notified of changes that only involve metadata (for example if no documents change but snapshot.metadata.fromCache
changes) you can use QueryListenOptions
when issuing your query:
https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/QueryListenOptions
这篇关于Firestore - 使用缓存直到在线内容更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!