'Forwarding a state in lambda causes recomposition even when state doesn't change

If X, Y are of type MutableState<String>, in the following snippet ComposableB, ComposableC and ComposableD are recomposed everytime X's state is changed.

Case 1

@Composable
fun ComposableA(
    val stateX: State<String>, // X
    val stateYProvider: () -> State<String>, // { Y }
) {
    ComposableB() {
        ComposableC(stateX.value)
        ComposableD(stateYProvider)
    }
}

But in the following snippet only ComposableB and ComposableC are recomposed everytime X's state is changed

Case 2

@Composable
fun ComposableA(
    val stateX: State<String>, // X
    val stateYProvider: () -> State<String>, // { Y }
) {
    ComposableB() {
        ComposableC(stateX.value)
        ComposableD({ stateYProvider() })
    }
}

Why is this so? Shouldn't Case 1 also recompose only ComposableB and ComposableC as ComposableD's arguments remain same when ComposableB's recomposition happens

Note: Passing states instead of values because every time the state changes ComposableA is getting recomposed, which is unnecessary



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source