Search code examples
androidmvvmviewmodel

Android - Observing global variable in ViewModel


I'm working on the login/logout module for my Android Application. I decided to hold the LoginUser instance in the Android Application class. Could the ViewModel observe a variable of the Application instance and update the UI? If not, how could I implement the login process?


Solution

  • You shouldn't hold your Login User instance in Application class. If you really need it, you can use it by dagger.

    Or you can use an User Repository. Where you can cache your user. If you want to observe the user, you use a LiveData which will send changes to your ui.

    class UserRepository(
    private val loginDataSource: LoginDataSource
    ) {
        // in-memory cache of the loggedInUser object
        var user: User? = null
            private set
    
        val isLoggedIn: Boolean
            get() = user != null
    
        init {
            // If user credentials will be cached in local storage, it is 
    recommended it be encrypted
            // @see https://developer.android.com/training/articles/keystore
            user = null
        }
    
        fun logout() {
            user = null
            loginDataSource.logout()
        }
    
        fun saveLoggedInUser(user: User) {
            this.user = user
            // If user credentials will be cached in local storage, it is 
     recommended it be encrypted
            // @see https://developer.android.com/training/articles/keystore
        }
    }
    

    You can also use a livedata here for loggged in user to observer in your viewmodel.