Cloud Firestore:通过直接获取检索缓存的数据吗?

Dan*_*e B 6 android firebase google-cloud-firestore

从服务器检索数据可能需要几秒钟。在此期间,有什么方法可以使用直接获取来检索缓存的数据?

onComplete似乎只有当数据从服务器检索被称为:

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

缓存的数据有回调吗?

tou*_*doy 5

现在可以仅从缓存版本加载数据。来自文档

您可以在 get() 调用中指定 source 选项以更改默认行为.....您只能从离线缓存中获取。

如果失败,那么您可以再次尝试在线版本。

例子:

DocumentReference docRef = db.collection("cities").document("SF");

// Source can be CACHE, SERVER, or DEFAULT.
Source source = Source.CACHE;

// Get the document, forcing the SDK to use the offline cache
docRef.get(source).addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            // Document found in the offline cache
            DocumentSnapshot document = task.getResult();
            Log.d(TAG, "Cached document data: " + document.getData());
        } else {
            Log.d(TAG, "Cached get failed: ", task.getException());
            //try again with online version
        }
    }
});
Run Code Online (Sandbox Code Playgroud)


Fra*_*len 3

我刚刚在 Android 应用程序中运行了一些测试,看看它是如何工作的。

无论您是从缓存还是从网络获取数据,您需要的代码都是相同的:

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

当我在线时打印:

isFromCache: false

当我离线时,它会打印:

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

当我在线时,我得到两张照片:

isFromCache: true

isFromCache: false

  • 即使有互联网连接,从缓存获取数据也非常有用,因为从服务器获取数据需要几秒钟的时间。 (6认同)