Home > Enterprise >  When should I detach my Firestore Listeners?
When should I detach my Firestore Listeners?

Time:11-21

I've been using my snapshot listeners and seems to cause a conflict whenever the user signed out. A toast message saying:

"PERMISSION_DENIED: Missing or Insufficient permissions." is immediately displayed.

Based on my research for answers, I have to detach my listeners as soon as I am done using it. It says that whenever the user signed out, the listeners (snapshot listeners) are still working in the background and since the auth is no longer present, It shows the above toast message.

Snippet:

Main Activity.kt

private fun getRealTimeUpdates(){
        productsCollectionRef.addSnapshotListener { snapshot, error ->
            error?.let {
                Toast.makeText(this, error.message, Toast.LENGTH_SHORT).show()
                return@addSnapshotListener
            }

            snapshot?.let {
                for(document in it){
                    suggestions.add(document["name"].toString())
                }

            }
        }
    }

//sign out
        binding.tvSignOut.setOnClickListener {

            FirebaseAuth.getInstance().signOut()

            Intent(this, LoginActivity::class.java).also {
                startActivity(it)
                finish()
            }
        }


As the title suggest, when and how should I detach my firebase listeners? When is the best time to use it?

CodePudding user response:

allow read, write: if true;

Can you try typing this in the firestore rule? Or undo the last changes.

CodePudding user response:

You need to disconnect your listeners BEFORE you logout the user.

I built a mechanism (extended from a Redux store, although that's not strictly necessary) that registers my listeners as a group (well, several groups because of several sub-accounts). When a logout is requested, the routine FIRST runs the unsubscribe(s), THEN logs-out the user and/or sub-account.

There are several ways to do this, but net:

  • login first, then add listeners
  • keep track of your listeners
  • ...
  • unsubscribe listeners
  • logout

I'll see if I can isolate some bits of the code (overall, my system is a fairly intricate mix of client, cloud and auth functionality)

  • Related