I have a suspend inner function inside a composable but it throws a compile time error stating that the method name cannot be resolved. Why is it not working?
CodePudding user response:
In order to call a suspend function inside of a composable function you have two options:
- Use
LaunchedEffectblock; - or use a
CoroutineScopeobject, which you can get usingrememberCoroutineScope.
Something like this:
@Composable
fun YourComposable() {
suspend fun innerFunc() {
// your code
}
// If you just need to call this function in the first composition
LaunchedEffect(Unit) {
innerFunc()
}
// But if you need to call in response of
// an event you should use coroutineScope
val scope = rememberCoroutineScope()
Button(onClick = {
scope.launch {
innerFunc()
}
}) {
Text("Button")
}
}
