Issue
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?
Solution
In order to call a suspend
function inside of a composable function you have two options:
- Use
LaunchedEffect
block; - or use a
CoroutineScope
object, 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")
}
}
Answered By - nglauber
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.