0

I've been checking out the Performance best practices for Jetpack Compose Google I/O, in there it's stated that this code should only re-execute the Text() function, since only this function reads a value that changes.

private class NameHolder(var name: String)

@Composable
private fun LittleText(nameHolder: NameHolder) {
    Box {
        Text(text = "Nombre: ${nameHolder.name}")
        println("compose 2")
    }
    println("compose 1")
}

however when I run it I can see that for every change both prints execute as well. I also tested with something like this:

@Composable
private fun LittleText(name: String) {
    Box {
        Text(text = "Nombre: $name")
        println("compose 2")
    }
    println("compose 1")
}

With the same result, I'm changing the text with a TextField, like this:

var name by remember { mutableStateOf("name") }

TextField(
   value = name,
      onValueChange = {
         name = it
      }
   )
    
LittleText(name)

What I'm I doing wrong? How can I achieve this behaviour and have only the Text re-executing the composition?

Jose Gonzalez
  • 1,491
  • 3
  • 25
  • 51
  • I think it refers to the UI will only ne updated if the value changes. The drawing process is "smart". – cutiko Aug 05 '22 at 13:11
  • 1
    @cutiko But that is not what he said, in another example he talks about the draw but in this particular example explains that the Text() should be the only one going throw the compose process. – Jose Gonzalez Aug 05 '22 at 14:21

1 Answers1

0

I found an answer that cover this:

@Composable
fun TestingCompose() {
    Column {
        TestView()
        println("compose 1")
    }
}

@Composable
fun TestView() {
    val textFieldValue = remember { mutableStateOf(TextFieldValue("")) }
    TextField(textFieldValue)
    println("compose 2")
}

@Composable
fun TextField(textFieldValue: MutableState<TextFieldValue>) {
    TextField(
        value = textFieldValue.value,
        onValueChange = { textFieldValue.value = it }
    )
    println("compose 3")
}

I'm still trying to fully understand it, so any insight would be greatly appreciated, but checking the log while testing this shows that only the composable containing the TextField gets re-executed with every character.

Jose Gonzalez
  • 1,491
  • 3
  • 25
  • 51