cprcrack cprcrack - 3 years ago 125
Android Question

On Firebase database, do I need to worry about calling FirebaseDatabase.goOffline()? When is the connection kept alive?

So I couldn't find any clear documentation regarding the use of FirebaseDatabase.goOffline(), only general advice that this method stops the connection to Firebase, thus saving "concurrent connections" which are limited or you have to pay for them.

But I'm not sure when is your connection alive and when you should call goOffline() and goOnline(). For example, my understanding is that a call to

like this would make your connection to be kept alive indefinitely listening to post changes:

ValueEventListener postListener = new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
// ...
// ...

But what if you only use
(notice Single) and other methods that should not require a continuous open connection such as
? I am safe that my app will not hold open connections that will count for Firebase as "concurrent connections" for more than a couple of seconds per call? (assuming decent internet connection)

Answer Source

The documentation describes:

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.

addListenerForSingleValueEvent() detaches the listener after the value is obtained and thus does not persist as an active listener. If you fetch all your data using that method, the connection will close after roughly a minute of inactivity.

You can monitor connection state using a listener at .info/connected. Example code is in the documentation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download