https://kotlinlang.org logo
#compose
Title
# compose
e

Ellen Spertus

08/17/2022, 2:50 AM
I'm reading Thinking in Compose and have some questions about this part:
In Compose, you call the composable function again with new data. Doing so causes the function to be recomposed--the widgets emitted by the function are redrawn, if necessary, with new data. The Compose framework can intelligently recompose only the components that changed.
For example, consider this composable function which displays a button:
```@Composable
fun ClickCounter(clicks: Int, onClick: () -> Unit) {
Button(onClick = onClick) {
Text("I've been clicked $clicks times")
}
}```
Every time the button is clicked, the caller updates the value of
clicks
.
I don't understand why the last sentence is true. We don't see the
onClick
function. Are we supposed to infer that it is
() -> clicks++
and that
clicks
is bound to the parameter?
b

Ben Trengrove [G]

08/17/2022, 2:53 AM
That sentence isn't saying that is what always happens. The "caller" is whoever is calling this code, not the code from the example. That sentence is true because it is telling you that is what is happening.
The point to understand I guess is that nothing will happen unless the caller updates whatever value they are passing into "clicks" and that is what causes the recomposition
e

Ellen Spertus

08/17/2022, 3:01 AM
Thanks for replying, @Ben Trengrove [G]. What's confusing me is that I don't see why clicking on the button causes
ClickCounter
to be called again. Are you saying that the
onClick
method calls
ClickCounter
?
If there were another button whose
onClick
method called
ClickCounter()
, I'd understand.
b

Ben Trengrove [G]

08/17/2022, 3:03 AM
Clicking on the button won't cause ClickCounter to be called again. That relys on the caller updating some compose state in order to change it, that compose state being used for "clicks" is what will end up causing ClickCounter to be called again via recomposition. It will end up looking like this
Copy code
@Composable
fun MyScreen() {
   var clickCount by remember { mutableStateOf(0) }
   ClickCounter(clickCount, onClick = { clickCount ++ })
}
e

Ellen Spertus

08/17/2022, 3:05 AM
I understand the code you provided. Are you saying that's how
ClickCounter
might be called?
b

Ben Trengrove [G]

08/17/2022, 3:06 AM
Yeah, it's just one way it could be. "Every time the button is clicked, the caller updates the value of clicks" is saying the caller is doing this. If for instance the onClick was empty, nothing would change
e

Ellen Spertus

08/17/2022, 3:07 AM
Thanks so much, @Ben Trengrove [G].
7 Views