Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it says "Calls to launch should happen inside a LaunchedEffect and not composition"?

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

1 Answers

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
    }
}
like image 54
nglauber Avatar answered Nov 19 '25 02:11

nglauber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!