Cloud Firestore: Get Cached Data Through Direct Access?

Retrieving data from the server may take several seconds. Is there a way to get cached data in the meantime using direct get?

onCompleteseems to be called only when data is retrieved from the server:

db.collection("cities").whereEqualTo("state", "CA").get()
        .addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                ...
                }
            }
        });

Is there a callback for cached data?

+4
source share
2 answers

I just checked a few tests in an Android app to see how it works.

The code you need is the same, regardless of whether you get data from the cache or from the network:

    db.collection("translations").document("rPpciqsXjAzjpComjd5j").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            DocumentSnapshot snapshot = task.getResult();
            System.out.println("isFromCache: "+snapshot.getMetadata().isFromCache());
        }
    });

When I am on the Internet, it prints:

isFromCache: false

When I go offline, it prints:

isFromCache: true

.

:

    db.collection("translations").document("rPpciqsXjAzjpComjd5j").addSnapshotListener(new DocumentListenOptions().includeMetadataChanges(), new EventListener<DocumentSnapshot>() {
            @Override
            public void onEvent(DocumentSnapshot snapshot, FirebaseFirestoreException e) {
                System.out.println("listen.isFromCache: "+snapshot.getMetadata().isFromCache());
            }
        }
    );

, :

isFromCache: true

isFromCache: false

+2

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


All Articles