我想在循环中运行一个挂起函数。
工作正常,但postValue
不是每次都更新值。它只调用观察者一次。在这里可以做些什么?
jobSearch = viewModelScope.launch(exceptionHandler) {
for (category in (searchCategories.value?.data ?: emptyList())) {
searchResponse.postValue(Resource.loading(null))
val response =
searchResultSource.getSearchResultFromRepo(
category?.id,
searchTerm,
1,
Constants.PAGE_SIZE_SEARCH
)
response?.let {
searchResponse.postValue(Resource.sucess(response))
} ?: run {
searchResponse.postValue(Resource.error("Something Went Wrong"))
}
}
}
postValue
方法将新值排队到Main Thread
中。如果你在主线程将这个值传递给观察者之前调用这个方法,它将用新的值替换旧的值。所以你的观察者总是读取最后发出的值。您需要用以下代码替换searchResponse.postValue
调用,以便将所有发出的值传递给观察者:
new Handler(Looper.getMainLooper()).post(() -> searchResponse.setValue(Resource.loading(null)));
new Handler(Looper.getMainLooper()).post(() -> searchResponse.setValue(Resource.sucess(response)));
new Handler(Looper.getMainLooper()).post(() -> searchResponse.setValue(Resource.error("Something Went Wrong")));