首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在jetpack中不工作的协同工作

在jetpack中不工作的协同工作
EN

Stack Overflow用户
提问于 2022-09-14 08:52:45
回答 1查看 81关注 0票数 0

我使用以下方法获取网络数据。

我在一个协同线中启动一个网络请求,但是它不能工作,分页负载不会被调用。

但是,如果我通过init方法在ViewModel中调用网络请求,我就可以成功地获取数据。

代码语言:javascript
复制
@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))
            }
        }
    }
}
代码语言:javascript
复制
@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)
    }
}

我不明白这两个电话有什么区别,为什么不起作用?

如有任何有帮助的意见和回答,我们将不胜感激。

EN

回答 1

Stack Overflow用户

发布于 2022-09-14 10:36:07

我解决了这个问题,在上面的代码中使用了两次协同线,导致网络数据不被获取。

--在这里使用协同线:

代码语言:javascript
复制
    fun getCountryList() {
        countryGroupList = Pager(config) {
            CountrySource()
        }.flow.cachedIn(viewModelScope)
    }

这里是另一个协同线:

代码语言:javascript
复制
    LaunchedEffect(true) {
        viewModel.getCountryList()  // Not working
    }

当前使用:

代码语言:javascript
复制
    val execute = rememberSaveable { mutableStateOf(true) }

    if (execute.value) {
        viewModel.getCountryList()
        execute.value = false
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73714088

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档