我有一个带有搜索功能的片段的视图模型。尽管对象列表反映在我的RecyclerView上,但我还是利用协程从API中提取了内容,然后使用结果设置了MediatorLiveData值。当我尝试使用liveData.value
访问MediatorLiveData值时,它返回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)
我的代码显示在上面,我已经被困了好几天了,任何帮助将不胜感激! }