Cloud Firestore: retrieving cached data via direct get?

前端 未结 3 1558
借酒劲吻你
借酒劲吻你 2020-12-16 21:44

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

The onComplete seem

3条回答
  •  既然无缘
    2020-12-16 22:11

    I just ran a few tests in an Android app to see how this works.

    The code you need is the same, no matter if you're getting data from the cache or from the network:

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

    When I'm online this prints:

    isFromCache: false

    When I go offline, it prints:

    isFromCache: true

    There is no way to force retrieval from the cache while you're connected to the server.

    If instead I use a listener:

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

    I get two prints when I'm online:

    isFromCache: true

    isFromCache: false

提交回复
热议问题