Search code examples
androidkotlinviewmodelandroid-livedatakotlin-null-safety

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.


Solution

  • Just use

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

    instead of

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