我使用以下方法获取网络数据。
我在一个协同线中启动一个网络请求,但是它不能工作,分页负载不会被调用。
但是,如果我通过init方法在ViewModel中调用网络请求,我就可以成功地获取数据。
@Composable
fun HomeView() {
val viewModel = hiltViewModel<CountryViewModel>()
LaunchedEffect(true) {
viewModel.getCountryList() // Not working
}
val pagingItems = viewModel.countryGroupList.collectAsLazyPagingItems()
Scaffold {
LazyColumn(
contentPadding = PaddingValues(horizontal = 16.dp, vertical = 96.dp),
verticalArrangement = Arrangement.spacedBy(32.dp),
modifier = Modifier.fillMaxSize()) {
items(pagingItems) { countryGroup ->
if (countryGroup == null) return@items
Text(text = "Hello", modifier = Modifier.height(100.dp))
}
}
}
}@HiltViewModel
class CountryViewModel @Inject constructor() : ViewModel() {
var countryGroupList = flowOf<PagingData<CountryGroup>>()
private val config = PagingConfig(pageSize = 26, prefetchDistance = 1, initialLoadSize = 26)
init {
getCountryList() // can work
}
fun getCountryList() {
countryGroupList = Pager(config) {
CountrySource()
}.flow.cachedIn(viewModelScope)
}
}我不明白这两个电话有什么区别,为什么不起作用?
如有任何有帮助的意见和回答,我们将不胜感激。
发布于 2022-09-14 10:36:07
我解决了这个问题,在上面的代码中使用了两次协同线,导致网络数据不被获取。
--在这里使用协同线:
fun getCountryList() {
countryGroupList = Pager(config) {
CountrySource()
}.flow.cachedIn(viewModelScope)
}这里是另一个协同线:
LaunchedEffect(true) {
viewModel.getCountryList() // Not working
}当前使用:
val execute = rememberSaveable { mutableStateOf(true) }
if (execute.value) {
viewModel.getCountryList()
execute.value = false
}https://stackoverflow.com/questions/73714088
复制相似问题