这可能是由于将 collectAsStateWithLifecycle() 放在单独的 Composable 中而导致的。为了解决这个问题,需要使用 LaunchedEffect 将 collectAsStateWithLifecycle() 放在同一个 Composable 中。以下是示例代码:
@Composable fun MyComposable(vm: MyViewModel) { var myState by remember { mutableStateOf("") } LaunchedEffect(Unit) { vm.myFlow.collectAsState().also { myState = it } } Text(text = myState) }
在这个示例中,我们在同一个 Composable 中使用了 LaunchedEffect,来管理 collectAsStateWithLifecycle()。由于 collectAsStateWithLifecycle() 被正确地放置在组合中,因此它能够正确地收集数据并更新 UI。