Abhiraj Sharma
Abhiraj Sharma

Reputation: 1

Purpose of removing the Firebase AuthStateListener for authentication on onPause() and adding it back on onResume()

I'm following a three day coarse of firebase chat app on udemy here https://classroom.udacity.com/courses/ud0352

According to them, I've attached the authStateListener for authentication on the onCreate().

mAuthStateListener = FirebaseAuth.AuthStateListener {
        val user: FirebaseUser? = it.currentUser
        if (user != null) {
            // User is signed in
            onSignedInInitialized(user.displayName)
        } else {
            // User is signed out
            onSignedOutCleanup()
        }
    }

Later the suggested removing the state listener on the onPause function and attaching it back on the onStart function without proper explanation.

override fun onPause() {
    super.onPause()
    if (mAuthStateListener !=null) {
        mFirebaseAuth!!.removeAuthStateListener(mAuthStateListener!!)
    }
    detachDatabaseReadListener()
    mMessageAdapter!!.clear()
}

override fun onResume() {
    super.onResume()
    mFirebaseAuth!!.addAuthStateListener(mAuthStateListener!!)
}

I'm new to Android dev and Firebase and still cannot figure out the purpose of removing the adapter and listener on these functions.

Upvotes: 0

Views: 248

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317497

Since your activity isn't at all visible to the user at onStop, it makes sense to stop things that might cause something to happen in your app that the user can't see. Likewise, your activity is visible again during onStart, so you'd want to re-establish any behaviors that should be visible.

I suggest reading through the documentation for Android lifecycle callbacks to better understand what they're used for.

Upvotes: 1

Related Questions