Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloud Firestore: retrieving cached data via direct get?

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

Is there any callback for the cached data?

like image 700
Daniele B Avatar asked Nov 10 '17 12:11

Daniele B


People also ask

How do I get fetch data from firestore?

There are two ways to retrieve data stored in Cloud Firestore. Either of these methods can be used with documents, collections of documents, or the results of queries: Call a method to get the data. Set a listener to receive data-change events.

Does firebase firestore cache?

Firestore supports offline data persistence. This feature caches a copy of the Firestore data that your app is actively using, so your app can access the data when the device is offline. You can write, read, listen to, and query the cached data.

Which function is used to fetch data from the firebase document?

The Get() function in Go unmarshals the data into a given data structure. Notice that we used the value event type in the example above, which reads the entire contents of a Firebase database reference, even if only one piece of data changed.

Does firestore use Websockets?

Firestore is using websockets under the hood to react to changes, plus all the optimization based on lessons learned after the original firebase realtime db, it will scale!


1 Answers

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

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.

Example:

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
        }
    }
});
like image 88
touhid udoy Avatar answered Oct 04 '22 11:10

touhid udoy