I created an app that just displays one icon, two texts, and two buttons. When by click on any button, the appropriate text updates, because it depends on the value passed in my function. But together with text, each time icon recomposes, it even doesn't depend on any value.
data class TestUIState(
val counterA: Int = 0,
val counterB: Int = 0,
)
@HiltViewModel
class TestViewModel @Inject constructor() : ViewModel() {
val uiFlow = MutableStateFlow(TestUIState())
val data: TestUIState
get() = uiFlow.value
fun increaseCounterA() {
uiFlow.value = data.copy(counterA = data.counterA + 1)
}
fun increaseCounterB() {
uiFlow.value = data.copy(counterB = data.counterB + 1)
}
}
@Composable
fun TestCompose(
uiValueState: State<TestUIState>,
increaseCounterA: () -> Unit,
increaseCounterB: () -> Unit,
) {
Column(modifier = Modifier.fillMaxSize()) {
Icon(
painter = painterResource(id = R.drawable.ic_google),
contentDescription = "",
)
Text(text = "CounterA: ${uiValueState.value.counterA}", color = Color.White)
Text(text = "Counter B: ${uiValueState.value.counterB}", color = Color.White)
Button(onClick = increaseCounterA) {
Text(text = "Increase counter A")
}
Button(onClick = increaseCounterB) {
Text(text = "Increase counter B")
}
}
}
setContent {
val testViewModel: TestViewModel = hiltViewModel()
TestCompose(
uiValueState = testViewModel.uiFlow.collectAsStateWithLifecycle(),
increaseCounterA = testViewModel::increaseCounterA,
increaseCounterB = testViewModel::increaseCounterB
)
}
When I press the update counter A button, I see the next in the layout inspector:
Then when I press the update counter B button, the icon recomposes again.
I just can't understand why a static image recomposes each time when some value even not related to this icon has changed. Or can it be expected behavior for this element? I'm not sure. Please help me to understand this issue.