Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expected non-nullable value for MutableLiveData

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.

like image 575
Aamer Paul Avatar asked Mar 07 '26 11:03

Aamer Paul


2 Answers

Just use

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

instead of

private val _users = MutableLiveData<List<User>>()
like image 200
NRUSINGHA MOHARANA Avatar answered Mar 08 '26 23:03

NRUSINGHA MOHARANA


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.

like image 40
Arst Avatar answered Mar 09 '26 00:03

Arst



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!