首页 > 解决方案 > 离线时强制从 Cloud Firestore 缓存中提取

问题描述

我目前正在将 Firebase Firestore 用于 Android 项目,但是当手机处于飞行模式时,我在检索数据时遇到了一些问题。这是我的代码:

public void loadThings() {
    FirebaseFirestore db = FirebaseFirestore.getInstance();

    db.collection("medidas").whereEqualTo("id_user", mAuth.getCurrentUser().getUid()).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                QuerySnapshot snapshot = task.getResult();
                int tam = snapshot.getDocuments().size();
                data = new String[tam];
                StringBuilder temp;
                DocumentSnapshot doc;
                for (int i = 0; i < tam; i++) {
                    temp = new StringBuilder();
                    doc = snapshot.getDocuments().get(i);

                    temp.append("Date: ").append(doc.get("fecha")).append(";");
                    temp.append("Min: ").append(doc.get("min")).append(";");
                    temp.append("Max: ").append(doc.get("max")).append(";");
                    temp.append("Avg: ").append(doc.get("avg")).append(";");


                    data[i] = temp.toString();
                }
                if(tam==0)
                {
                    noMeasures();
                }
            }
            else
            {
                data=null;
            }
            mLoadingIndicator.setVisibility(View.INVISIBLE);
            mMeasuresAdapter.setMeasuresData(data);
            if (null == data) {
                showErrorMessage();
            } else {
                showMeasuresDataView();
            }
        }
    });
}

具体问题是有时显示数据需要很长时间(超过 10 秒),而另一些则需要立即显示数据。由于手机处于飞行模式,很明显我正在检索的数据来自缓存。但是,我不明白为什么有时需要这么长时间。有没有办法明确告诉firestore从缓存中获取数据而不是尝试从服务器获取数据?提前致谢

标签: javaandroidfirebasegoogle-cloud-firestore

解决方案


有没有办法明确告诉firestore从缓存中获取数据而不是尝试从服务器获取数据?

是的,从16.0.0SDK 版本更新开始,您可以借助DocumentReference.get(Source source)Query.get(Source source)方法来实现这一点。

默认情况下,get()通过等待来自服务器的数据,尽可能尝试提供最新数据,但如果您处于脱机状态且无法访问服务器,它可能会返回缓存数据或失败。可以通过 Source 参数更改此行为。

因此,您可以将作为参数传递给DocumentReference或源,Query以便我们可以强制从或 尝试服务器检索数据并回退到缓存。server onlychache only

所以在代码中可能看起来像这样:

FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference docIdRef = db.collection("yourCollection").document("yourDocument");
docIdRef.get(Source.CACHE).addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
    @Override
    public void onSuccess(DocumentSnapshot documentSnapshot) {
        //Get data from the documentSnapshot object
    }
});

在这种情况下,我们强制从CACHE唯一检索数据。如果您想强制从SERVER唯一检索数据,您应该作为参数传递给get()方法,Source.SERVER. 更多信息在这里


推荐阅读