I have noticed that after turning off the internet connection and than turning it back on (while my Android
app
is still running, in the background or not), it takes the Firestore
module a pretty long time to regain the connection to the server (about a minute), and I can't make any Firestore
operations until the connection is regained.
Is this a normal behavior?
If it does, can I somehow check the Firestore
module current connection status? (in order to limit my user's actions if there is a need).
val() === true) { alert("connected"); } else { alert("not connected"); } });
You can listen to a document with the onSnapshot() method. An initial call using the callback you provide creates a document snapshot immediately with the current contents of the single document. Then, each time the contents change, another call updates the document snapshot.
As far as i know, there is no equivalent to Firebase Realtime Database's .info/connected
in Cloud Firestore, that allows you to verify the connection status. I read on Firebase offical blog a post regarding the differences between Firebase and Firestore and i saw that this problem is in fact one of the use-cases.
The Realtime Database has native support for presence -- that is, being able to tell when a user has come online or gone offline. While we do have a solution for Cloud Firestore, it's not quite as elegant.
If you read Firestore offical documentation, you will see that there is a possible implementation of a presence system by combining Realtime Database and Firestore.
I'm currently testing a fix for this that seems to be working.
Step 1: Ensure the device has a data connection using Android's recommended approach
public static boolean isConnectedToInternet(@NonNull Context _context) {
ConnectivityManager cm = (ConnectivityManager)_context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null)
return false;
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
Step 2: Force Firestore to connect (the idea is to override Firestore's internal connection retry exponential backoff)
FirebaseFirestore.getInstance().enableNetwork()
Step 3 (optional): If you're doing this when your app is in the background, you may also want to use Android's Task API to synchronously wait until the enableNetwork() Task completes. Otherwise, the OS may think your background work is complete, and cut off your app's access to system resources (network, CPU, etc).
try { Tasks.await(FirebaseFirestore.getInstance().enableNetwork()); }
catch (Exception e) {
Log.e(TAG, "error in Firestore enableNetwork(): ", e);
return;
}
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