Android Create Singleton LiveData to Observe Changes (e.g. User Login and Logout) - Kotlin

Apr 21, 2019

Create Singleton Object

object App {    class User(val id: String, val name: String, val isAdmin: Boolean)    var currentUser: User?        get() = currentUserLiveData.value        set(value) {            currentUserLiveData.postValue(value)        }    val currentUserLiveData = MutableLiveData<User?>()}

When user sign in/login.

App.currentUser = App.User("5pSFOxspzl75hYZzjnut", "Desmond Lua", true)

When user sign off/logout.

App.currentUser = null

Observer changes in Activity/Fragment.

App.currentUserLiveData.observe(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.