Zhang Zihan
07/23/2025, 3:48 AMval 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:
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)Adrien de Sentenac
07/23/2025, 6:00 AMLocalDensity.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-usageStylianos Gakis
07/23/2025, 6:02 AMZhang Zihan
07/23/2025, 6:22 AMderivedStateOf
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?
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...Stylianos Gakis
07/23/2025, 7:12 AMZach Klippenstein (he/him) [MOD]
07/23/2025, 2:41 PMZach Klippenstein (he/him) [MOD]
07/23/2025, 2:42 PMZhang Zihan
07/23/2025, 3:57 PMremember
instead? Is it worth it?
val density = LocalDensity.current
var textHeight by remember { mutableIntStateOf(0) }
val iconHeight = remember(density, textHeight) { with(density) { textHeight.toDp() - 2.dp } }
Stylianos Gakis
07/23/2025, 4:00 PMNino
07/23/2025, 4:00 PMremember
still costs a bit to check between the (re)compositions the keys. You better let the computer do its best : crush numbersZach Klippenstein (he/him) [MOD]
07/23/2025, 4:02 PM