简体   繁体   English

从ViewModel观察存储库LiveData并通知UI

[英]Observing repository LiveData from ViewModel and notify UI

Google says that is not possible to observe a LiveData from a ViewModel: Google表示无法从ViewModel观察LiveData:

[...] However ViewModel objects must never observe changes to lifecycle-aware observables, such as LiveData objects.[...] [...]但是,ViewModel对象必须永远不会观察到对生命周期感知的可观察对象的更改,例如LiveData对象。[...]

And I would handle the repo.login() result in the ViewModel and notify the UI thought the two SingleLiveEvent s, is it possible? 我会处理ViewModel中的repo.login()结果并通知UI认为两个SingleLiveEvent ,是否可能?

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

}

I think that the official guideline is to combine multiple livedatas in the ViewModel using a transformation . 我认为官方指南是使用转换在ViewModel中组合多个liveatas。 However usually I prefer to use livedatas only in the communication between the ViewModel and the View, in the repositories I use RxJava or coroutines. 但是通常我更喜欢只在ViewModel和View之间的通信中使用liveatas,在我使用RxJava或coroutines的存储库中。 So in your example I'd modify the login method in the repository to return a Single instead of a livedata and subscribe to it in the ViewModel. 因此,在您的示例中,我将修改存储库中的login方法以返回Single而不是livingata,并在ViewModel中订阅它。 You can then cancel the subscription when the ViewModel is destroyed. 然后,您可以在销毁ViewModel时取消订阅。 You can find an example of this architecture in this repository . 您可以在此存储库中找到此体系结构的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM