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)