将 LiveData<Resource<User>> 转换为 LiveData<User> 时的类型干扰问题

Type interference issue when Transforming LiveData<Resource<User>> to LiveData<User>

我正在尝试结合 Android Architecture GitHub example with databinding. To do so, I think I have to add an additional transformation from LiveData> to a LiveData in the UserViewModel:

val userResourceLiveData: LiveData<Resource<User>> = Transformations.switchMap(_login) { login ->
    if (login == null) {
        AbsentLiveData.create()
    }
    else {
        repository.loadUser(login)
    }
}

val userLiveData: LiveData<User> = Transformations.switchMap(userResourceLiveData) { userResource ->
    if (userResource == null) { // Error 1 on 'if'
        AbsentLiveData.create() // Error 2 on 'create()'
    }
    else {
        MutableLiveData(userResource.data)
    }
}

但是,出现了 2 个错误:

1) type inference for control flow expression failed, please specify its type explicitly.

2) Type inference failed: not enough information to infer parameter T in fun create(): LiveData

如果我将代码更改为:

if (userResource == null) {
   AbsentLiveData.create<User>()
}

然后switchMap开始抱怨:

Type inference failed: Cannot infer type parameter Y in ...

1) 为什么这不一样?我没想到根本需要类型定义,因为 <LiveData<Resource<User>>> 的映射以相同的方式正常工作。

2) 如何解决错误?

3) 这种应用数据绑定的解决方案可能是错误的方法吗?

The commit with this specific issue on GitHub repo

这对我有用:

        if (userResource == null) {
            AbsentLiveData.create<User>()
        }
        else {
            MutableLiveData(userResource.data!!)
        }