Firestore offline cache

2019-03-18 18:44发布

I'm building an Android application which has to work offline for weeks, but can sync immediately with a remote DB as it goes online.

My question is can Firestore be a good option for this? How long does Firestore keep its offline cache?

2条回答
狗以群分
2楼-- · 2019-03-18 19:21

Firestore can be configured to persist data for such disconnected/offline usage. I recommend that you read the enable offline persistence section in the docs, which contains this sample of enabling this feature:

FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
        .setPersistenceEnabled(true)
        .build();
db.setFirestoreSettings(settings);

This persistence is actually enabled by default on Android and iOS, so the call above is not needed.

You Android code that interact with the database will be the same whether you're connected or not, since the SDK simply works the same. If you want to detect whether data is coming from the cache (and thus potentially stale), read the section Listen to offline data in the docs.

The data in the cache does not expire after a certain amount of time. The only two reasons data is removed from the cache:

  1. The data has been removed from the server, in which case the client will remove it from the disk cache.
  2. The client needs to purge its disk cache to make space for more recent data.
查看更多
趁早两清
3楼-- · 2019-03-18 19:24

If you listen to data in Cloud Firestore, you will get immediate snapshots of cached data and also updates when your app is able to connect online:

final DocumentReference docRef = db.collection("cities").document("SF");
docRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
    @Override
    public void onEvent(@Nullable DocumentSnapshot snapshot,
                        @Nullable FirebaseFirestoreException e) {
        if (e != null) {
            Log.w(TAG, "Listen failed.", e);
            return;
        }


        // Determine if the data came from the server or from cache
        String source = snapshot != null && snapshot.getMetadata().hasPendingWrites()
                ? "Local" : "Server";


        // Read the data
        if (snapshot != null && snapshot.exists()) {
            Log.d(TAG, source + " data: " + snapshot.getData());
        } else {
            Log.d(TAG, source + " data: null");
        }
    }
});

Persistence is enabled by default so this behavior does not require any configuration.

查看更多
登录 后发表回答