首页 > 解决方案 > 可组合调用只能在可组合函数的上下文中发生

问题描述

我有查询需要致电scope.launch

   composeView {
            MyTheme {
                // Create a CoroutineScope that follows this composable's lifecycle
                val composableScope = rememberCoroutineScope()
                LaunchedEffect(key1 = "", block = {
                    composableScope.launch {
                        val b: Boolean = database.query()
                    }
                })
            }

现在我想传递bComposble

@Composable
    private fun Content(b: Boolean) {

    }

我应该怎么称呼 Content since @Composable invocations can only happen from the context of a @Composable function?如果我将内容放在启动块中,我会收到上述错误消息。

标签: androidandroid-jetpack-compose

解决方案


您可以使用作用域进行后台调用,例如从数据库中获取数据,并利用可变状态将其传递给可组合对象。

例如:

val foo = remember { mutableStateOf("") } 

LaunchedEffect(true) { 
  foo.value = bar()
}

Text (text = foo.value)

推荐阅读