Optimize firestore querysnapshot listener for read in android

Viewed 208

I am very new to Cloud Firestore and have some doubts regarding the querylistener read count. As most of the answer suggested on stack overflow that, we should attach the listener in onStart() and detach in OnStop() in the Android activity. I am building an app in which I have to attach the listener on Dashboard Activity and the user will navigate back and forth between dashboard and other activity frequently. So,

  1. when the user navigates to another activity the listener will be detached (onStop()) and if they come back it will be attached again (onStart()). And suppose between this, nothing has changed in documents on the server, will I still be charged for all read count even though nothing has changed on the server?

  2. Should I keep the listener attach and detach only when the user kills the app? By doing this, I will be only charged for the document which is changed while the app is in the foreground and not the all-read count if navigates between Dashboard and other activity.

1 Answers

we should attach the listener in onStart() and detach in OnStop() in the Android activity

If you are attaching a listener for getting real-time updates, yes, you need to remove the listener according to the life-cycle of the activity, as explained in my answer from the following post:

However, if you simply create a get() call, followed by addOnCompleteListener(), there is no listener that needs to be removed.

And to answer your first questions. It depends. If you are using a SnapshotListener and nothing is changed on the server, you'll always read the data from the cache. So you can go back and forth, as long as you want. But also keep in mind, that if the listener is disconnected for more than 30 minutes, you’ll be charged for reads as if we had issued a brand-new query. On the other hand, if you are using get(), you'll be charged with a number of read operation that is equal to the number of documents that you get, every time you call it, even if there is nothing changed on the server.

Why?

In order to provide up-to-date data, the Firestore SDK needs to check the online version of the documents against the cached one. That’s the reason why you are charged, regardless of what exists in the cache or if something is changed or not on the server.

To answer your second question, if you are using a SnapshotListener, you should always consider removing the listener, otherwise, your app will remain synchronized until Android OS will eventually close the app. It doesn't really matter if the app is in the foreground or in the background, if the listener stays active, you'll always be charged accordingly. You can find more info in the following article:

Related