【问题标题】:Observing repository LiveData from ViewModel and notify UI从 ViewModel 观察存储库 LiveData 并通知 UI
【发布时间】:2018-02-04 02:58:43
【问题描述】:

Google 表示无法从 ViewModel 观察 LiveData:

[...] 但是 ViewModel 对象绝不能观察到 生命周期感知的可观察对象,例如 LiveData 对象。[...]

我会在 ViewModel 中处理 repo.login() 结果并通知 UI 认为这两个 SingleLiveEvents,这可能吗?

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:将状态和数据包装在一个类中并公开它:developer.android.com/topic/libraries/architecture/…
  • @JemshitIskenderov,不是这个问题的答案。我想你会包装状态和数据,然后将其公开给 UI,我将处理 ViewModel 中的状态/数据并通过不同的 LiveData (SingleLiveEvent) 通知 UI。此外,您的解决方案假定 UI 会在轮换时更新,因为您应该公开从存储库返回的 LiveData。我会更新一次 UI,这就是我使用 SingleLiveEvent 的原因。

标签: android mvvm kotlin android-architecture-components


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-05-10
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多