小编dro*_*rcc的帖子

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

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 …
Run Code Online (Sandbox Code Playgroud)

android mvvm kotlin android-architecture-components

6
推荐指数
1
解决办法
4998
查看次数