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

时间:2021-05-10 03:12:05

标签: android kotlin android-jetpack-compose

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

@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}")
                }
            }
        }

    }

1 个答案:

答案 0 :(得分:0)

你应该这样做:

@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() 
    }
}