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

dro*_*rcc 6 android mvvm kotlin android-architecture-components

Google 表示无法从 ViewModel 观察 LiveData:

[...] 然而,ViewModel 对象绝不能观察生命周期感知可观察对象的变化,例如 LiveData 对象。[...]

我会repo.login()在 ViewModel 中处理结果并通知 UI 认为两个SingleLiveEvent 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

}
Run Code Online (Sandbox Code Playgroud)

小智 1

我认为官方指南是使用转换来组合 ViewModel 中的多个实时数据。然而,通常我更喜欢仅在 ViewModel 和 View 之间的通信中使用 livedatas,在存储库中我使用 RxJava 或协程。因此,在您的示例中,我将修改login存储库中的方法以返回 aSingle而不是 livedata 并在 ViewModel 中订阅它。然后,您可以在 ViewModel 被销毁时取消订阅。您可以在此存储库中找到此架构的示例。