Android Firebase Auth AuthStateListener as LiveData (lifecycle-aware)

April 8, 2019
FirebaseAuthLiveData
class FirebaseAuthLiveData(private val auth: FirebaseAuth) : SingleLiveEvent<FirebaseUser?>(), FirebaseAuth.AuthStateListener {
    private var lastUid: String? = null

    override fun onActive() {
        super.onActive()
        auth.addAuthStateListener(this)
    }

    override fun onInactive() {
        super.onInactive()
        auth.removeAuthStateListener(this)
    }

    override fun onAuthStateChanged(auth: FirebaseAuth) {
        // only trigger when user changed
        if (lastUid != auth.currentUser?.uid) {
            lastUid = auth.currentUser?.uid
            value = auth.currentUser
        }
    }
}

Usage

val authLiveData = FirebaseAuthLiveData(FirebaseAuth.getInstance())


authLiveData.owner(this, Observer { user ->
    // do something
})
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.