In below code I have used animateDpAsState and it recompose function only once but button recompose multiple times.
@Composable
fun MoveText() {
LogCompositions("JetpackCompose.app", "========CustomText function")
var visible by remember { mutableStateOf(true) }
val iconOffsetAnimation: Dp by animateDpAsState(
if (visible) 13.dp else 0.dp,
tween(1000), label = ""
)
val textOffsetAnimation: Dp by animateDpAsState(
if (visible) 19.dp else 5.dp,
tween(1000), label = ""
)
Column(
modifier = Modifier
.fillMaxSize()
.padding(start = 16.dp, top = 16.dp)
) {
Column {
Icon(
modifier = Modifier
.graphicsLayer { translationY = iconOffsetAnimation.toPx() },
imageVector = Icons.Default.ShoppingCart,
tint = Color.Black,
contentDescription = null,
)
Text(
modifier = Modifier
.graphicsLayer { translationY = textOffsetAnimation.toPx() },
text = "Hello, Anna",
fontSize = 20.sp,
color = Color.Black,
)
}
Button(
modifier = Modifier
.padding(top = 30.dp),
onClick = {
visible = !visible
},
) {
LogCompositions("JetpackCompose.app", "Button")
Text(text = "Move Text")
}
}
}
class Ref(var value: Int)
// Note the inline function below which ensures that this function is essentially
// copied at the call site to ensure that its logging only recompositions from the
// original call site.
@Composable
inline fun LogCompositions(tag: String, msg: String) {
val ref = remember { Ref(0) }
SideEffect { ref.value++ }
Log.d(tag, "Compositions: $msg ${ref.value}")
}
As in below image you can see function is recompose only 1 time but button recomposition happened 11 times.
Don't know why this happy. Is there any thing that I did wrong.
I don't know this is normal or we can fix this problem. Any help would be appreciated. Thanks.
As per @Gabriele Mariotti suggestion, I added LogCompositions in Button as well as in MoveText() function.
Surprisingly in logs I have seen that Button is not recompose that is as expected behavior.
Now I had scratch my head why in layout inspector it shown 11 times count of button recomposition.
Because every time adding logs to check recomposition is not feasible or best way as per my point of view.
Can anyone suggest on this why this is happening? Thanks