Home > Mobile >  How to call inner function inside composable?
How to call inner function inside composable?

Time:07-09

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 LaunchedEffect block;
  • or use a CoroutineScope object, which you can get using rememberCoroutineScope.

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")
    }
}
  • Related