Cloud Firestore:通过直接获取检索缓存数据? [英] Cloud Firestore: retrieving cached data via direct get?

查看:25
本文介绍了Cloud Firestore:通过直接获取检索缓存数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从服务器检索数据可能需要几秒钟.有没有办法在此期间使用直接获取检索缓存数据?

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

onComplete 似乎只有在从服务器检索数据时才会调用:

The onComplete seems to be called only when the 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()) {
                ...
                }
            }
        });

缓存数据有回调吗?

推荐答案

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

Now it is possible to load data only from cached version. From docs

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

You can specify the source option in a get() call to change the default behavior.....you can fetch from only the offline cache.

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

If it fails, then you can again try for the online version.

示例:

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

这篇关于Cloud Firestore:通过直接获取检索缓存数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆