Android Firebase Auth AuthStateListener as LiveData (lifecycle-aware)

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})

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.