Ivan Patrice
Ivan Patrice

Reputation: 129

How to stop getting data in Firestore?

I'm building an app using Firestore as my backend. I need to get every new change from database.

Code

EventListener<DocumentSnapshot> listener = new EventListener<DocumentSnapshot>() {
    @Override
    public void onEvent(@Nullable DocumentSnapshot snapshot, @Nullable FirebaseFirestoreException e) {
        if (snapshot != null && snapshot.exists()) {
            DataClass dataClass = snapshot.toObject(DataClass.class);
            processesData(dataClass); // process data from db.
        }
    }
};

ListenerRegistration listenerReg = dataDocumentReference.addSnapshotListener(listener);

When I close the application, the app is still getting the data.

I read that I can close the connection. How can I do that?

Upvotes: 3

Views: 2296

Answers (2)

giudigior
giudigior

Reputation: 146

You can pass the activity in the addSnapshotListener, so Firestore can clean up the listeners automatically when the activity is stopped.

ListenerRegistration listenerReg = dataDocumentReference.addSnapshotListener(MainActivity.this, listener);

I've added MainActivity just as an example. You have to add your Activity to make it work.

Upvotes: 1

Alex Mamo
Alex Mamo

Reputation: 138969

In order to solve this, you need to stop listening for changes and this can be done in your onStop() method by calling remove() method on your ListenerRegistration object like this:

@Override
protected void onStop() {
    super.onStop();

    if (listenerReg != null) {
        listenerReg.remove();
    }
}

Remember, when you are using addSnapshotListener you attach a listener that gets called for every change that takes place in your database. So this is happening also when your app is closed so it's mandatory to detach the listeners before the activity gets destroyed.

If in your app you don't need to get the data in real-time, you can the use a get() call directly on the reference, which just reads the document only once. Since it only reads once, there is no listener to be removed. This is the correspondent of addListenerForSingleValueEvent() used in the Firebase Realtime database.

As also @giudigior said in his answer, you can also pass your activity as the first argument in the addSnapshotListener() method, so Firestore can clean up the listeners automatically when the activity is stopped.

ListenerRegistration listenerReg = dataDocumentReference
            .addSnapshotListener(YourActivity.this, listener);

Upvotes: 3

Related Questions