Why does this code get executed twice? If recomposition... what triggers the recomposition?

794 Views Asked by At

I am Learning Android Compose, And I was looking/playing with this code from developers.android, in github. The projects is a simple app to demonstrate adaptive screen. Sports App

Everything works fine, but am a but confused.

I logged an item/line to Logcat. And I see that it gets executed twice? Recomposition? What is causing it?Screenshot of AS code

1

There are 1 best solutions below

2
On BEST ANSWER

In your code:

Log.i("info", "xxx")

Column(
    modifier = Modifier.padding(4.dp)
) {

    Box {
        Image(painter = painterResource(R.drawable.xx))
        Text()
    }

    Text(
        text = stringResource(R.string.app_name),
    )
}

The stringResource and painterResource can cause recomposition. In compose when something triggers a recomposition, it happens in the nearest scope.
However the Box and the Column are inline function, and it means that both don't have an own recompose scopes.

In your code when the Image and the Text are recomposed all the composable is recomposed.

If you change your Column into a custom Composable it won't be recomposed.

Something like:

@Composable
private fun MyColumn() {
    //same code above
}

and then:

Log.i("info", "xxx")
MyColumn()