Android-在ViewModel中观察全局变量

时间:2020-11-02 03:05:29

标签: android mvvm viewmodel

我正在为我的Android应用程序登录/注销模块。我决定将LoginUser实例保留在Android Application类中。 ViewModel是否可以观察Application实例的变量并更新UI?如果没有,我该如何执行登录过程?

2 个答案:

答案 0 :(得分:0)

您可以将登录的用户存储在Room DB中。 提取上次登录的用户作为实时数据,并在任何地方进行观察

答案 1 :(得分:0)

您不应将您的Login User实例保存在Application类中。如果确实需要它,可以用匕首来使用它。

或者您可以使用用户存储库。您可以在其中缓存用户的位置。如果要观察用户,请使用LiveData,它将把更改发送到用户界面。

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

您还可以在此处使用实时数据,以便在视图模型中将用户登录到观察者。