且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何删除本地缓存中的可用状态?

更新时间:2023-02-22 21:33:22

您可以通过检查其元数据来确定快照是否来自缓存。 p> QuerySnapshot#getMetadata( ) 返回一个 SnapshotMetadata 对象。
SnapshotMetadata#如果快照来自缓存,则isFromCache() 将返回一个布尔值。



如果您希望在元数据更改时收到通知(所以你可以知道 isFromCache()变化),那么当你添加监听器的时候你必须传递选项:

  //创建选项
QueryListenOptions options = new QueryListenOptions()。includeDocumentMetadataChanges();

//添加侦听器时传递它们
collectionReference.addSnapshotListener(options,new EventListener< QuerySnapshot>(){
// ...
}) ;

请参阅 addSnapshotListener


So I am working on an app that uses firebase's firestore and was wondering if this is possible because I don't want my app to check for data that no longer exists in the server.

Example:

collectionReference.addSnapshotListener(new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(QuerySnapshot snapshots, FirebaseFirestoreException e) {
            for (DocumentSnapshot snapshot : snapshots) {
                System.out.println(snapshot.getId());
                // This prints document IDs of documents that were deleted
                // from the collection when the app was not running
            }
        }
    });


Using DocumentSnapshot.exists() to filter snapshots existing only in the server does not work


More info in this page:

The initial state can come from the server directly, or from a local cache. If there is state available in a local cache, the query snapshot will be initially populated with the cached data, then updated with the server's data when the client has caught up with the server's state.

You can determine if the snapshot comes from the cache by checking its metadata.

QuerySnapshot#getMetadata() returns a SnapshotMetadata object. SnapshotMetadata#isFromCache() returns a boolean if the snapshot is from the cache.

If you want to be notified whenever the metadata changes (so you can know if isFromCache() changes) then you have to pass options when you add the listener:

   // Create options
   QueryListenOptions options = new QueryListenOptions().includeDocumentMetadataChanges();

   // Pass them when you add the listener
   collectionReference.addSnapshotListener(options, new EventListener<QuerySnapshot>() {
       // ...
   });

See the docs for addSnapshotListener