Expected non-nullable value for MutableLiveData
Asked Answered
C

2

10
private val _users = MutableLiveData<List<User>>()
val users: LiveData<List<User>> get() = _users

fun getUsers() {
    viewModelScope.launch {
        _users.value = users()
    }
}

suspend fun users(): List<User> {
    TODO("Not implemented")
}

I get following error on _users.value = users()

Expected non-nullable value. Inspection info: This check ensures that LiveData values are not null when explicitly declared as non-nullable.

I'm using lifecycle version 2.3.1. The problem seems to be with suspend function users(). If I remove the suspend modifier it works fine.

Consubstantial answered 7/4, 2021 at 12:0 Comment(0)
B
12

Just use

private val _users: MutableLiveData<List<User>> = MutableLiveData()

instead of

private val _users = MutableLiveData<List<User>>()
Blandish answered 7/4, 2021 at 12:25 Comment(4)
These should be equivalent meaning. It appears to be an Android Lint bug. Do you know if this is documented anywhere or reported on the AOSP bug tracker?Mycetozoan
No, I dont find any documentation yet, but I use this to get rid of error.Blandish
It is weird, also _users.postValue(users()) made it runnable without error.Andreasandree
This didn't work for me.. The answer below did however.Euniceeunuch
I
11

Try this._users.value = users(). Adding this at the front works for me. Not sure why. In your case you might need this@yourModel._users.value = users() since you are calling it in the viewModelScope.

Instantaneity answered 13/2, 2022 at 6:27 Comment(1)
This worked for me - the updated IDE has started to flag these, when it didn't before (also when updating LiveData in my ViewModels)..Euniceeunuch

© 2022 - 2024 — McMap. All rights reserved.