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

时间:2018-02-04 02:58:43

标签: android mvvm kotlin android-architecture-components

Google表示无法从ViewModel观察LiveData:

  

[...]但是ViewModel对象必须永远不会观察到更改   生命周期感知的可观察对象,例如LiveData对象。[...]

我会处理ViewModel中的repo.login()结果并通知用户界面认为这两个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

}

1 个答案:

答案 0 :(得分:0)

我认为官方指南是使用transformation在ViewModel中组合多个liveatas。但是通常我更喜欢只在ViewModel和View之间的通信中使用liveatas,在我使用RxJava或coroutines的存储库中。因此,在您的示例中,我将修改存储库中的login方法以返回Single而不是livingata,并在ViewModel中订阅它。然后,您可以在销毁ViewModel时取消订阅。您可以在此repository中找到此体系结构的示例。