2017-10-17 17 views
1

所以我正在研究一個使用firebase的firestore的應用程序,並想知道這是否可能,因爲我不希望我的應用程序檢查服務器中不再存在的數據。

例子:
如何刪除本地緩存中的可用狀態?

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 
      } 
     } 
    }); 


使用DocumentSnapshot.exists()過濾快照只存在於服務器不this page工作


更多信息:

初始狀態可以來從服務器直接或從本地緩存。如果本地緩存中存在可用狀態,則查詢快照將首先填充緩存的數據,然後在客戶端趕上服務器狀態時使用服務器數據更新。

回答

1

您可以通過檢查其元數據來確定快照是否來自緩存。

QuerySnapshot#getMetadata()返回一個SnapshotMetadata對象。 SnapshotMetadata#isFromCache()如果快照來自緩存,則返回布爾值。

如果您希望收到通知每當元數據更改(這樣你就可以知道,如果isFromCache()變化),那麼你有當您添加聽者傳遞選項:

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

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

請參閱該文檔爲addSnapshotListener