Is there a strategy that would work within the current Firebase offering to detect if the server connection is lost and/or regained?
I'm considering some offline contingencies for mobile devices and I would like a reliable means to determine when the Firebase data layer is available.
If you want to know if the client is connected to the server before calling setValue() , you can attach a listener to . info/connected .
Firebase has great option of using their database and sending data to their db even if you are offline, and then when the connection is up again, it sends automatically the data to the db.
This is a commonly requested feature, and we just released an API update to let you do this!
var firebaseRef = new Firebase('http://INSTANCE.firebaseio.com'); firebaseRef.child('.info/connected').on('value', function(connectedSnap) { if (connectedSnap.val() === true) { /* we're connected! */ } else { /* we're disconnected! */ } });
Full docs are available at https://firebase.google.com/docs/database/web/offline-capabilities.
Updated: 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. Here is an example:
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"); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With