0

I just having a certain problem about the Firestore snapshot listener. I am new on using it and I had read that you have to stop the snapshot listener everytime you move to another activity. I tried:

db.collection("Mydata").document(userID).addSnapshotListener(itemView.getContext(), new EventListener<DocumentSnapshot>() {
                    @Override
                    public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {

                    }
                })

But it has an error because of the itemView.getContext().

My questions are:

  • Is it okay if I don't include the Activity in and leave the snapshotlistener like that?
  • If not, Is there any way to solve this?
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Mr. Baks
  • 297
  • 2
  • 6
  • 20

1 Answers1

1

Is it okay if I don't include the Activity in and leave the snapshotlistener like that?

No, it is not! When you are calling addSnapshotListener for listening to realtime updates, it means that 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, that's why it's mandatory to detach the listeners before the activity gets destroyed.

If not, Is there any way to solve this?

Yes, there is. Please see my answer from the following post:

If in your app you don't need to get the data in realtime, then you can simply 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.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193