首页 > 解决方案 > 在 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)

我的代码如上所示,我已经被困了好几天了,任何帮助将不胜感激!}

标签: androidandroid-livedataandroid-architecture-componentskotlin-coroutinesandroid-architecture-lifecycle

解决方案


显然这个问题是由ViewModel我的适配器中的注入引起的。我用匕首在我的适配器中注入了我的视图模型,并onClickListener用函数设置了按钮selectUser()。我将设置提取clickListener到我的片段中并且它起作用了。


推荐阅读