I'm trying to combine the 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)
}
}
However, there are 2 errors showing up:
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 I change the code to this:
if (userResource == null) {
AbsentLiveData.create<User>()
}
then switchMap starts complaining:
Type inference failed: Cannot infer type parameter Y in ...
1) Why isn't this working the same? I didn't expect a type definition was required at all, because the mapping for <LiveData<Resource<User>>> worked properly in the same way.
2) How to solve the errors?
3) Might this solution to apply databinding be the wrong approach alltogether?
userResource.datais typeUser?- Sanlok LeeuserResource.data's type is aUser?, it returnsLiveData<User?>so it might not match with the method signature. Have you tried doing something likeMutableLiveData(userResource.data!!)? - Sanlok LeeUser?, however, I don't see any errors on that line. Changing it to aMutableLiveData(userResource.data!!)doesn't change a thing. There's only errors on the places I pointed out in comments. You could fork my repo if you need more info. - P KuijpersMutableLiveData(userResource.data!!)though. However, the app immediately crashes on that line, becauseuserResource.data== null initially! - P Kuijpers