I am new in jetpack compose , I try to build small project to learn jetpack compose, I have example code , and for
composableScope.launch
it throw an error as a Calls to launch should happen inside a LaunchedEffect and not composition for launch
, any idea?
val composableScope = rememberCoroutineScope()
val currentPage = onBoardViewModel.currentPage.collectAsState()
Scaffold(
modifier = Modifier.fillMaxSize(),
scaffoldState = scaffoldState
) {
Surface(
modifier = Modifier.fillMaxSize()
) {
composableScope.launch {
pagerState.animateScrollToPage(
page = currentPage.value
)
}
}
}
CodePudding user response:
You can't directly call a coroutine in a "composition" (the place in your Composable function where you're declaring your UI) because this function can be called any time and several times by the Compose framework.
Instead, you should use LaunchedEffect
if you want to call a coroutine during a composition (read more here). Or if you need a coroutine in an event (like a click) you should use the rememberCoroutineScope
.
LaunchedEffect(someKey) { // the key define when the block is relaunched
// Your coroutine code here
}
or
Modifier.clickable {
coroutineScope {
// your coroutine here
}
}