Firestore - 使用缓存直到在线内容更新

Die*_*cia 14 persistence caching offline download google-cloud-firestore

我从Firestore开始.我已经阅读了有关离线数据持久性的文档和教程,但我还不清楚Firestore是否会再次下载数据,即使内容尚未修改.例如,如果我有一个查询,结果将每周更新一次,我不需要应用程序再次下载内容,直到进行更改,编写代码的效率方面的最佳方法是什么?谢谢!

Sam*_*ern 8

您希望使用"快照侦听器"API来收听您的查询:https: //firebase.google.com/docs/firestore/query-data/listen#listen_to_multiple_documents_in_a_collection

这里有一些JavaScript作为例子:

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(", "));
    });
Run Code Online (Sandbox Code Playgroud)

第一次连接此侦听器时,Firestore将访问网络以将所有结果下载到您的查询中,并为您提供查询快照,如您所期望的那样.

如果第二次连接相同的侦听器并且您正在使用脱机持久性,则将立即使用缓存中的结果触发侦听器.以下是检测结果是来自缓存还是本地的方法:

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);
      });
  });
Run Code Online (Sandbox Code Playgroud)

获得缓存结果后,Firestore将检查服务器以查看查询结果是否有任何更改.如果是,您将获得有关更改的另一个快照.

如果您希望收到仅涉及元数据的更改通知(例如,如果没有文档更改但snapshot.metadata.fromCache更改),您可以QueryListenOptions在发出查询时使用:https: //firebase.google.com/docs/reference/android/com/google/火力/公司的FireStore/QueryListenOptions

  • 我不认为这是准确的.根据文档,Firestore将默认首先尝试服务器数据,只有在失败时它才会回退到缓存.https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/Source (7认同)