android-jetpack-composekotlin-stateflowcomposable

Separate instance of classes calling Composable function


Let's say I have some kind of structure like this:

data class C(val value: Int) {
    @Composable
    fun MyComposable() {
        Text("Value: $value")
    }
}

@Composable
fun ParentComposable(stateFlow: StateFlow<C>) {
    val state by stateFlow.collectAsState()
    state.MyComposable()
}

I'm assuming the composable will be treated as an entirely separate instance and the whole thing will need to be recomposed (no children skipped even). Is this correct?


Solution

  • There are several issues with your code:

    When you fix all of the above your original question becomes moot. For the sake of completeness, though: Since the function belongs to the class and not the instance, and the class never changes, the composable will be recognized as the same one and no additional recompositions will take place. MyComposable is recomposed only when the new C instance has a different value.