2
votes

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?

The commit with this specific issue on GitHub repo

1
userResource.data is type User? - Sanlok Lee
What I was trying to say was because userResource.data's type is a User?, it returns LiveData<User?> so it might not match with the method signature. Have you tried doing something like MutableLiveData(userResource.data!!) ? - Sanlok Lee
You're right, it's a User?, however, I don't see any errors on that line. Changing it to a MutableLiveData(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 Kuijpers
If I leave out the complete if-else statement, then I DO need to define it as MutableLiveData(userResource.data!!) though. However, the app immediately crashes on that line, because userResource.data == null initially! - P Kuijpers

1 Answers

1
votes

This works for me:

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