https://kotlinlang.org logo
Title
a

Arjan van Wieringen

04/27/2023, 5:41 PM
A basic compose question. If the inputs of a Composable are the same, it is skipped right? However, in my case:
@Composable fun Icons(
    icons: List<IconState> = listOf(),
    iconEventHandler: IconEventHandler? = null,
) {
    icons.forEach { element ->
        Icon(
            iconState = element,
            onClick = { iconEventHandler?.onClick(element) },
            onDragStart = { offset -> iconEventHandler?.onDragStart(element, offset) },
            onDrag = { offset -> iconEventHandler?.onDrag(element, offset) },
            onDragEnd = { iconEventHandler?.onDragEnd(element) }
        )
    }
}
The icons states are the same, but the lambda's passed to the Icon composable have different hashcodes every time, and as such it rerenders. I guess it makes sense, because Kotlin can not determine structural equality of lambdas. However, this must be a common pitfall then? What could I do to improve the performance? Push the
iconEventHandler
insode the
Icon
composable?
i

Ian Lake

04/27/2023, 6:40 PM
Have you considered using
rememberUpdatedState
? That's what can capture a lambda as a long-lived state object that doesn't change hashcodes: https://developer.android.com/jetpack/compose/side-effects#rememberupdatedstate
a

Arjan van Wieringen

04/27/2023, 7:04 PM
Sure. But isn’t passing lambdas to composables are very very basic function? I haven’t seen rememberUpdatedState anywhere in documentation for this?
i

Ian Lake

04/27/2023, 7:09 PM
Recomposition, by itself, is not a problem or something that indicates a performance issue. You actually need to trace to see if that recomposition is actually expensive
And I'm pretty sure I just linked to the documentation, right alongside DisposableEffect and other APIs 🙂
a

Arjan van Wieringen

04/27/2023, 7:27 PM
Yes I understand. And thanks for your help!
f

Francesc

04/28/2023, 2:09 AM
note that
List
is not stable, if you want to avoid recompositions with collections consider using immutable collections
a

Arjan van Wieringen

04/28/2023, 5:17 AM
At @Francesc , I already to that in the underlying view model. List is the interface, PersistentList is the implementation