Android-在ViewModel中观察全局变量



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

您不应该将Login User实例保存在Application类中。如果你真的需要它,你可以用dagger。

或者您可以使用用户存储库。可以缓存用户的位置。如果你想观察用户,你可以使用LiveData,它会将更改发送到你的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
}
}

您也可以在这里使用livedata,以便在您的视图模型中登录用户到观察者。

您可以将登录的用户存储在Room DB中。获取最后一个登录的用户作为实时数据,并在任何地方观察

最新更新