简体   繁体   English

MutableLiveData 的预期不可为空值

[英]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()我在_users.value = users()上收到以下错误

Expected non-nullable value.预期的不可为空的值。 Inspection info: This check ensures that LiveData values are not null when explicitly declared as non-nullable.检查信息:此检查确保 LiveData 值在明确声明为不可为空时不是 null。

I'm using lifecycle version 2.3.1 .我正在使用生命周期版本2.3.1 The problem seems to be with suspend function users().问题似乎在于暂停 function users()。 If I remove the suspend modifier it works fine.如果我删除挂起修饰符,它工作正常。

Just use private val _users:MutableLiveData<List<User>> = MutableLiveData() instead of private val _users = MutableLiveData<List<User>>() .只需使用private val _users:MutableLiveData<List<User>> = MutableLiveData()而不是private val _users = MutableLiveData<List<User>>()

Try this._users.value = users() .试试this._users.value = users() Adding this at the front works for me.在前面添加this对我有用。 Not sure why.不知道为什么。 In your case you might need this@yourModel._users.value = users() since you are calling it in the viewModelScope.在您的情况下,您可能需要this@yourModel._users.value = users()因为您在 viewModelScope 中调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 可空值和不可空值 - Nullable and non-nullable values 无法将不可为空的 LiveData 值设置为 null - Cannot set non-nullable LiveData value to null 不可为空的实例字段 - Non-Nullable instance field 为什么可以将 java 可空返回值分配给 Kotlin 非可空变量? - Why can a java nullable returned value be assigned to a Kotlin Non-Nullable variable? 声明为不可为空的 Kotlin 属性即使具有初始化值也是可为空的 - Kotlin property declared as non-nullable is nullable even if it has initialized value 为什么 Kotlin 在声明为不可为空字符串的属性中接受空值? - Why is Kotlin accepting a null value in an attribute declared as a non-nullable string? 不可为空的实例字段 '_bmi' 必须初始化 flutter - Non-nullable instance field '_bmi' must be initialized flutter Flutter - 如何处理小部件属性的非空实例 - Flutter - How to handle Non-Nullable Instance of widget properties 如何创建可以保存 state 的不可为空的 LiveData - How to create a non-nullable LiveData that can save state Kotlin 单元测试变量声明 lateinit vs lazy vs nullable vs non nullable - Kotlin Unit Test variable declaration lateinit vs lazy vs nullable vs non-nullable
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM