android - 在 viewModelScope 中设置后 LiveData 值为 null
问题描述
我有一个带有搜索功能的片段的视图模型。我使用协程从 API 中获取数据,然后使用结果设置 MediatorLiveData 值,尽管对象列表反映在我的 RecyclerView 上。当我尝试使用 访问 MediatorLiveData 值时liveData.value
,它返回 null。我尝试过调试它,但尽管显示了对象列表,但我无法真正访问 ViewModel 中 livedata 的值
视图模型
class SearchViewModel @Inject constructor(private val mutwitsRepo: MutwitsRepo) : BaseViewModel() {
val query = MutableLiveData<String>()
private val _isLoading = MutableLiveData<Boolean>()
val isLoading: LiveData<Boolean> = _isLoading
private val _users = MediatorLiveData<List<User>>()
val users: LiveData<List<User>> = _users
private var queryTextChangedJob: Job? = null
init {
_users.addSource(query) { queryStr ->
if (queryStr.isNullOrEmpty()) _users.value = emptyList()
else searchUsers(queryStr)
}
}
fun searchUsers(query: String) {
_isLoading.value = true
queryTextChangedJob?.cancel()
queryTextChangedJob = viewModelScope.launch {
delay(300)
_users.value = mutwitsRepo.searchUsers(query)
_isLoading.value = false
}
}
fun selectUser(user: User) {
val temp = _users.value
temp?.find { it.id_str == user.id_str }?.toggleSelected()
_users.value = temp
}
override fun onCleared() {
super.onCleared()
queryTextChangedJob?.cancel()
}
}
存储库功能
suspend fun searchUsers(query: String): List<User> = withContext(Dispatchers.IO) {
return@withContext twitterService.searchUsers(query)
我的代码如上所示,我已经被困了好几天了,任何帮助将不胜感激!}
解决方案
显然这个问题是由ViewModel
我的适配器中的注入引起的。我用匕首在我的适配器中注入了我的视图模型,并onClickListener
用函数设置了按钮selectUser()
。我将设置提取clickListener
到我的片段中并且它起作用了。
推荐阅读
- java - 单击任何按钮时如何显示加载gif
- jquery - 带有 jquery datepicker 错误的 jquery 验证插件(请输入有效日期)
- jquery - How to pass rendering angular js html string to html page
- python - 无法使用 Tkinter 按钮停止一段时间
- sql - 同一 cloumn 上两个值的百分比差异
- r - R中的文件排序列表
- c++ - glutMotionFunc“翻转”问题
- flutter - 使用堆栈的拖动小部件更新所有附加的小部件
- arrays - 对节点js中的对象数组进行排序?
- android - Android 进度条不旋转并在奥利奥中出现箭头