使用协同程序在ViewModel内部获取LiveData值的问题

时间:2019-12-30 17:17:20

标签: android android-livedata android-architecture-components kotlin-coroutines android-architecture-lifecycle

我有一个带有搜索功能的片段的视图模型。尽管对象列表反映在我的RecyclerView上,但我还是利用协程从API中提取了内容,然后使用结果设置了MediatorLiveData值。当我尝试使用liveData.value访问MediatorLiveData值时,它返回null。我已经尝试调试它,但是尽管显示了对象列表,但实际上无法在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()
  }

}

存储库功能

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

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

0 个答案:

没有答案