Hi everyone! I'm using the following code in Compo...
# compose
z
Hi everyone! I'm using the following code in Compose:
Copy code
val density = LocalDensity.current
var textHeight by remember { mutableIntStateOf(0) }
val iconHeight by remember { derivedStateOf { with(density) { textHeight.toDp() - 2.dp } } }
In theory, when the screen density changes (e.g. I move the window to another monitor with a different zoom),
iconHeight
should change and trigger a recompose. But it doesn't, it keeps the old value. I need to explicitly specify the
key
to cause
remember
to change:
Copy code
val iconHeight by remember(density) { derivedStateOf { with(density) { textHeight.toDp() - 2.dp } } }
Is this a bug? (I've only tested
Compose Desktop 1.9.0-beta01
so far)
a
This is not a bug, this is because
LocalDensity.current
is not a Compose state object so
derivedStateOf
does not react when it changes. Also, this is an incorrect usage of derivedStateOf. You only want to use derivedStateOf if the value it produces changes less often than the state it observes. See https://developer.android.com/develop/ui/compose/side-effects#incorrect-usage
s
derivedState can only "magically" read updates on values it uses when they're backed by mutableState. Does not look to be the case for LocalDensity.current
z
Thanks! I wrapped it in
derivedStateOf
because I need to call
iconHeight
in multiple Icons and I want to cache the value to reduce unnecessary calculations. But as you said, this is not correct. So should I write it like this?
Copy code
val density = LocalDensity.current
var textHeight by remember { mutableIntStateOf(0) }
val iconHeight = with(density) { textHeight.toDp() - 2.dp }
This seems to be a bit confusing to me. I remember that some articles said that writing like this will cause additional calculations to be generated at each recompose, while other articles said that writing like this will cause some calculations to be skipped...
s
I don't know which ones you've read, but I'd personally recommend you just read this one https://blog.zachklipp.com/how-derivedstateof-works-a-deep-d-er-ive/
z
Additional calculations are fine if they’re cheap - dSO has its own costs, and computers happen to be really good at subtracting one number from another.
🤮 1
🙈 1
In this case even remembering the calculation (without dSO) isn’t worth it, it’s so simple
🤮 1
🙈 1
z
What if I use
remember
instead? Is it worth it?
Copy code
val density = LocalDensity.current
var textHeight by remember { mutableIntStateOf(0) }
val iconHeight = remember(density, textHeight) { with(density) { textHeight.toDp() - 2.dp } }
n
remember
still costs a bit to check between the (re)compositions the keys. You better let the computer do its best : crush numbers
z
You’re literally just doing like 2 math operations, not even allocating anything. I don’t know why you are so concerned with caching this.