How to call child composable lambda

Viewed 580
@Composable
fun Root() {
    Scaffold(
            floatingActionButton = {
                FloatingActionButton(onClick = {}) {
                    Icon(Icons.Filled.Favorite)
                }
            }
    ) {
        Child()
    }
}

@Composable
fun Child() {
    var textField1 by remember { mutableStateOf("") }
    TextField(value = textField1, onValueChange = {textField1 = it})

    val validateAndMakeNetworkRequest = {

    }
}

How can I call validateAndMakeNetworkRequest from floating action button without state hoisting? The code above just example, Child composable could be very deep

1 Answers

Actually, you don't. In Jetpack Compose, we are not really calling funcions, there's a gradle plugin working some magic to simplfy our code, but, what's actually happening is that we are saying to the runtime "hey, this is the function I want to call" and the runtime calls it as many times as it sees fit to compose the screen.

It's easy to notice that if you out a Log.d("some", "thing") inside a composable function, the app may log it many times, even if we don't do anything.

I know that you sad "without state hoisting", but that's not how declarative works. You need a boolean stored in a state and an "if" using it whether to call a composable or not.

In case of a network request, you can separate it in a normal function, and call it inside you FloatingActionButton onClick.

Related