Force fetch from Cloud Firestore cache when offline

I'm currently using Firebase Firestore for an Android Project but I'm having some trouble retrieving data when the phone is on Airplane mode. Here's my code:

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

The specific problem is that sometimes it takes to long to show the data (more than 10 seconds) while some others it shows the data inmediatly. Since the phone is on airplane mode is obvious that the data I'm retrieving comes from the cache. However, I don't understand why it is taking so long sometimes. Is there some way to tell firestore explicitly to bring data from the cache instead of trying to fetch it from the server? Thanks in advance

Upvotes: 0

Views: 1244

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

Is there some way to tell firestore explicitly to bring data from the cache instead of trying to fetch it from the server?

Yes it is, starting with the 16.0.0 SDK version update, you can achieve this with the help of the DocumentReference.get(Source source) and Query.get(Source source) methods.

By default, get() attempts to provide up-to-date data when possible by waiting for data from the server, but it may return cached data or fail if you are offline and the server cannot be reached. This behavior can be altered via the Source parameter.

So you can pass as an argument to the DocumentReference or to the Query the source, so we can force the retrieval of data from the server only, chache only or attempt server and fall back to the cache.

So in code might look like this:

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

In this case, we force the data to be retrieved from the CACHE only. If you want to force the data to be retrieved from the SERVER only, you should pass as an argument to the get() method, Source.SERVER. More informations here.

Upvotes: 5

Related Questions