Android 从ViewModel观察存储库LiveData并通知UI
谷歌表示,不可能从ViewModel中观察LiveData: […]但是,ViewModel对象决不能观察对的更改 生命周期感知的可观察对象,如LiveData对象。[…] 我会处理ViewModel中的Android 从ViewModel观察存储库LiveData并通知UI,android,mvvm,kotlin,android-architecture-components,Android,Mvvm,Kotlin,Android Architecture Components,谷歌表示,不可能从ViewModel中观察LiveData: […]但是,ViewModel对象决不能观察对的更改 生命周期感知的可观察对象,如LiveData对象。[…] 我会处理ViewModel中的repo.login()结果,并通知UI这两个s,这可能吗 class Repository { // .... // fun login(user:String, password:String): LiveData<Status> { /* ... */ } }
repo.login()
结果,并通知UI这两个s,这可能吗
class Repository {
// .... //
fun login(user:String, password:String): LiveData<Status> { /* ... */ }
}
class LoginViewModel : ViewModel() {
@Inject
lateinit var repo: Repository
private var auth = MutableLiveData<User>()
private var showErrorEvent = SingleLiveEvent<String>()
private var showSuccessEvent = SingleLiveEvent<String>()
// Called from UI
fun performLogin(user:User){
repo.login(user.name, user.password)
// We can't observe the result here
// and update error/success events
}
// Called from UI
fun getErrorEvent() = showErrorEvent
// Called from UI
fun getSuccessEvent() = showSuccessEvent
}
类存储库{
// .... //
有趣的登录(用户:String,密码:String):LiveData{/*…*/}
}
类LoginViewModel:ViewModel(){
@注入
lateinit var repo:存储库
私有var auth=MutableLiveData()
private var-showerrorvevent=SingleLiveEvent()
私有变量showSuccessEvent=SingleLiveEvent()
//从UI调用
趣味performLogin(用户:用户){
repo.login(user.name、user.password)
//我们无法在这里观察结果
//并更新错误/成功事件
}
//从UI调用
fun getErrorEvent()=淋浴事件
//从UI调用
fun getSuccessEvent()=showSuccessEvent
}
我认为官方的指导方针是使用。然而,通常我更喜欢只在ViewModel和视图之间的通信中使用livedatas,在我使用RxJava或协同程序的存储库中使用livedatas。因此,在您的示例中,我将修改存储库中的login
方法,以返回Single
而不是livedata,并在ViewModel中订阅它。然后,当ViewModel被销毁时,可以取消订阅。您可以在此中找到此体系结构的示例。选项1:将状态和数据包装在类中并公开:@JemshitIskenderov不是此问题的答案。我设想您将包装状态和数据,然后将其公开给UI,我将在ViewModel中处理状态/数据,并通过不同的LiveData(SingleLiveEvent)通知UI。在本例中,您的解决方案假定UI在轮换时得到更新,因为您应该公开从存储库返回的LiveData。我会更新一次UI,这就是我使用SingleLiveEvent的原因。