首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >@Composable调用只能在@Composable函数的上下文中发生

@Composable调用只能在@Composable函数的上下文中发生
EN

Stack Overflow用户
提问于 2021-05-10 11:12:06
回答 1查看 196关注 0票数 1

如何从corrutines的上下文中调用可组合函数?我尝试了下面的代码,但是我得到了错误。

代码语言:javascript
复制
@Composable
    fun ShowItems(){
        var ListArticle = ArrayList<Article>()
        lifecycleScope.launchWhenStarted {
            // Triggers the flow and starts listening for values
            viewModel.uiState.collect { uiState ->
                // New value received
                when (uiState) {
                    is MainViewModel.LatestNewsUiState.Success -> {
                        //Log.e(TAG,"${uiState.news}")
                        if(uiState.news != null){
                            for(i in uiState.news){
                                ListArticle.add(i)
                            }
                            context.ItemNews(uiState.news.get(4))
                            Log.e(TAG,"${uiState.news}")
                        }
                    }
                    is MainViewModel.LatestNewsUiState.Error -> Log.e(TAG,"${uiState.exception}")
                }
            }
        }

    }
EN

回答 1

Stack Overflow用户

发布于 2021-05-11 02:25:55

你应该这样做:

代码语言:javascript
复制
@Composable
fun ShowItems(){
    val uiState = viewModel.uiState.collectAsState()
    // Mount your UI in according to uiState object
    when (uiState.value) {
       is MainViewModel.LatestNewsUiState.Success -> { ... }
       is MainViewModel.LatestNewsUiState.Error -> { ... }
    }
    // Launch a coroutine when the component is first launched
    LaunchedEffect(viewModel) {
        // this call should change uiState internally in your viewModel
        viewModel.loadYourData() 
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67464331

复制
相关文章

相似问题

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