Android - 在 ViewModel 中观察全局变量
Android - Observing global variable in ViewModel
我正在为我的 Android 应用程序开发 login/logout 模块。我决定在 Android Application
class 中保留 LoginUser
实例。 ViewModel
可以观察 Application 实例的变量并更新 UI 吗?如果没有,我该如何实现登录过程?
您可以将登录的用户存储在 Room DB 中。
获取最后登录的用户作为 livedata 并在任何地方观察它
您不应在应用程序 class 中保留您的登录用户实例。实在需要的话可以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
}
}
您还可以在此处使用实时数据将已登录用户转为视图模型中的观察者。
我正在为我的 Android 应用程序开发 login/logout 模块。我决定在 Android Application
class 中保留 LoginUser
实例。 ViewModel
可以观察 Application 实例的变量并更新 UI 吗?如果没有,我该如何实现登录过程?
您可以将登录的用户存储在 Room DB 中。 获取最后登录的用户作为 livedata 并在任何地方观察它
您不应在应用程序 class 中保留您的登录用户实例。实在需要的话可以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
}
}
您还可以在此处使用实时数据将已登录用户转为视图模型中的观察者。