Raj Narayanan
Raj Narayanan

Reputation: 3422

How to call inner function inside composable?

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?

Upvotes: 2

Views: 4259

Answers (1)

nglauber
nglauber

Reputation: 23894

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

Upvotes: 3

Related Questions