简体   繁体   English

在 viewModelScope 中设置后 LiveData 值为 null

[英]LiveData value is null after setting in viewModelScope

I have a viewmodel for a fragment with a search functionality.我有一个具有搜索功能的片段的视图模型。 I made use of Coroutines to fetch from the API and then set the MediatorLiveData value with the result, although the list of objects are reflected on my RecyclerView.我使用协程从 API 中获取数据,然后使用结果设置 MediatorLiveData 值,尽管对象列表反映在我的 RecyclerView 上。 When I try to access the MediatorLiveData value with liveData.value , it returns null.当我尝试使用liveData.value访问 MediatorLiveData 值时,它返回 null。 I've tried debugging it but despite displaying the list of objects, I can't really access the value of the livedata in the ViewModel我试过调试它,但尽管显示了对象列表,但我无法真正访问 ViewModel 中 livedata 的值

ViewModel视图模型

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()
  }

}

Repository Function存储库功能

suspend fun searchUsers(query: String): List<User> = withContext(Dispatchers.IO) {
  return@withContext twitterService.searchUsers(query)

My codes are shown above, I've been stuck for days now and any help would be much appreciated!我的代码显示在上面,我已经被困了好几天了,任何帮助将不胜感激! } }

Apparently this problem was caused by the injection of ViewModel in my adapter.显然这个问题是由在我的适配器中注入ViewModel引起的。 I injected my viewmodel in my adapter with dagger and set the button's onClickListener with the function selectUser() .我注入我的视图模型在我的适配器与匕首和设置按钮的onClickListener与功能selectUser() I extracted the setting of clickListener to my fragment and it worked.我将clickListener的设置提取到我的片段中并且它起作用了。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM