Firebase database for Android - write events when

2020-04-08 11:45发布

问题:

As stated in the title, I am using the Firebase Realtime Database, with persistence enabled.

As stated in the guide,

By enabling persistence, any data that the Firebase Realtime Database client would sync while online persists to disk and is available offline, even when the user or operating system restarts the app. This means your app works as it would online by using the local data stored in the cache. Listener callbacks will continue to fire for local updates.

While this happens with the ValueEventListeners and every read listener, I can't find a way to make it work with write operations as well. This is a snippet from my database helper class:

    DatabaseReference userRef = root.child("users").child(user.getUid());
    userRef.setValue(user).addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void result) {
            //handle success event
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            //handle failure event
        }
    });

Even with persistence enabled, that should make the database behave in a "reactive fashion", these two listeners will not fire until the database goes online again and finally pushes the updates to the server.

This isn't really what I was hoping for, since I expected the event to be triggered once the data was cached locally. I know I could simply ignore the events and pretend it succeeded, but I was wondering, am I missing something? Is there a way to trigger the events as soon as the data is cached?

回答1:

The onSuccess listener of a write operation is triggered when the data is written to the database on the server.

There is no event that triggers when the data has been written to the local queue.