Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Database differentiate between online and offline data

I know that the Firebase Realtime Database provides offline support, but how can I differentiate between data provided by an online connection or local offline changes?

like image 977
Nishu Avatar asked Oct 24 '25 21:10

Nishu


1 Answers

The Firebase Database provides a specific method to know if a client is connected or not.

Google wrote a handy documentation on that topic.

From the provided link:

Detecting Connection State

For many presence-related features, it is useful for a client to know when it is online or offline. Firebase Realtime Database clients provide a special location at /.info/connected which is updated every time the client's connection state changes.

DatabaseReference connectedRef = FirebaseDatabase.getInstance().getReference(".info/connected");
connectedRef.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot snapshot) {
    boolean connected = snapshot.getValue(Boolean.class);
    if (connected) {
      System.out.println("connected");
    } else {
      System.out.println("not connected");
    }
  }
  @Override
  public void onCancelled(DatabaseError error) {
    System.err.println("Listener was cancelled");
  }
});

/.info/connected is a boolean value which is not synchronized between clients because the value is dependent on the state of the client. In other words, if one client reads /.info/connected as false, this is no guarantee that a separate client will also read false.

On Android, Firebase automatically manages connection state to reduce bandwidth and battery usage. When a client has no active listeners, no pending write or onDisconnect operations, and is not explicitly disconnected by the goOffline method, Firebase closes the connection after 60 seconds of inactivity.

Knowing if your client is connected to the database will help differentiate between data provided from online and offline storage. I am pretty sure there is no specific way to see if a DataSnapshot comes from online or offline data.

like image 117
Rodrigo Ehlers Avatar answered Oct 27 '25 12:10

Rodrigo Ehlers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!