Why Kotlin Compose function dont recompose

77 Views Asked by At

In the process of debugging, I noticed something that I cannot explain to myself. Here is my example

Column {
       var text by remember {
               mutableStateOf("")
        }

        TextField(value = text, onValueChange = { text = it })
        Image(
              painter = painterResource(id = R.drawable.mypos_world_white),
              contentDescription = null
        )
}

Everything is clear here, we enter the text, and we get a recomposition of both the text of the field and the picture, as painterResource is marked as unstable.

Layout Inscpector Result

Ffter i bring the picture into a separate function the behavior changes

//call site
Column {
    var text by remember {
        mutableStateOf("")
    }

    TextField(value = text, onValueChange = { text = it })
    ImageFunction()
}

@Composable
fun ImageFunction() {
    Image(
            painter = painterResource(id = R.drawable.mypos_world_white),
            contentDescription = null
    )
}

Layout Inscpector Result Now recomposition is skipped.

Shuld we bring all unstable components, like Images, out of main scope, and why this works like this?

1

There are 1 best solutions below

0
On

A couple possible reasons:

  1. https://www.reddit.com/r/androiddev/comments/16rsmj5/did_you_know_that_painter_is_not_stable_and/ <- painter resource may not be stable (yet) so it may be worth to export the image to an external function that takes in a drawableResource as a parameter (HOWEVER, you may use the ImageVector which seems to be already marked as immutable, see this)
  2. the Image Composable is part of the same scope as the TextField. Since they share the same scope, any change in one will cause the other to recompose. This is because the Image Composable is marked as unstable (painterResource), so it triggers a recomposition whenever its value changes.