Why does it matter if I call a composable from wit...
# compose
u
Why does it matter if I call a composable from within a
when
in every branch, vs. producing a value with the
when
and calling the composable with the result? Former seems to lag the scrolling, while latter doesn’t
Copy code
Code in thread
Copy code
@Composable
private fun MyContent(
    state: AirPodsBatteryCheckerState,
    scrollState: ScrollState
) {
    when (state) {
        AirPodsBatteryCheckerState.Connecting -> Body(null, scrollState)
        is AirPodsBatteryCheckerState.Connected -> Body(state.airPodsBatteryLevel, scrollState)
        is AirPodsBatteryCheckerState.Error -> Body(AirPodsBatteryLevel(0, 0, 0), scrollState)
    }
}

@Composable
private fun MyContent2(
    state: AirPodsBatteryCheckerState,
    scrollState: ScrollState
) {
    val batteryLevel = when (state) {
        AirPodsBatteryCheckerState.Connecting -> null
        is AirPodsBatteryCheckerState.Connected -> state.airPodsBatteryLevel
        is AirPodsBatteryCheckerState.Error -> AirPodsBatteryLevel(0, 0, 0)
    }
    Body(batteryLevel, scrollState)
}
f
The first variant removes the entire
Body
UI tree and replaces it with new one. The second variant just updates input params.
u
I hear what you’re saying but I don’t see it 😄 Isn’t the seconds doing the same? and then it gets diffed internally etc.
f
I don't think this works like this. If I remember correctly, in
MyContent
compose compiler inserts replacable group which switches between two different
Body
nodes.
u
because of the control flow?
if
when
, something else?
f
Exactly
u
something else to watch out for?
f
Probably any code with conditional logic where only one output is possible 🤷
u
Blbe je ze si to vsimnem len tak ze scrollovanie lagne, co moze lagovat aj tak v debug mode
f
Source code KDoc
A replacable group is a group that cannot be moved during execution and can only either inserted, removed, or replaced. For example, the group created by most control flow constructs such as an
if
statement are replacable groups.
Blbe je ze si to vsimnem len tak ze scrollovanie lagne, co moze lagovat aj tak v debug mode
It's not that hard to notice in code. If there is
if
,
when
or any other conditional logic, expect the UI to be
replaced
instead of
restarted
. Also please write in english so people can use search and find relevant information 🙏
z
Composable identity is always tied to source code location, unless using
movableContentOf
. Calling the exact same composable with the exact same arguments from two different places in source will result in completely different state being spun up, maintained, and torn down for each.
a
It’s also not just the singular source code location of where a particular composable is being called, it’s the source code locations of the whole call hierarchy.