https://kotlinlang.org logo
Title
v

vide

06/24/2022, 11:13 AM
I feel like am missing something fundamental from my mental model of how compose works 😅, could anyone point me to the right direction? I am trying to use a value from LocalConfiguration in a heavy-ish calculation like this:
val calculationResult by remember { derivedStateOf {
    val primaryLocale = LocalConfiguration.current.locales.get(0) // error
    // Some filtering, calculations, etc.
} }
Obviously this doesn't work, since CompositionLocal.current is @Composable and results in an error. If I store the Configuration outside of the derivedStateOf block, it won't work either since it doesn't observe that State is being read and won't update.
val configuration = LocalConfiguration.current
val calculationResult by remember { derivedStateOf {
    val primaryLocale = configuration.locales.get(0)
    // Some filtering, calculations, etc.
} }
// Doesn't update
What would be an idiomatic/correct way to achieve what I'm trying to do here?
o

Oleksandr Balan

06/24/2022, 11:44 AM
It doesn’t observe that State, because you
remember
it without key, which means once calculated it will not change till Composable leaves the composition. Either remove
remember
, or add
configuration
as a
key
, so that the whole
remember
content will be recalculated when
configuration
changes:
val configuration = LocalConfiguration.current
val calculationResult by remember(configuration) { derivedStateOf {
    val primaryLocale = configuration.locales.get(0)
    // Some filtering, calculations, etc.
} }
s

Sean McQuillan [G]

06/24/2022, 4:58 PM
whetever you read any captured variables in a remember block, you probably need to add them to key
☝️ 2
v

vide

06/27/2022, 8:26 AM
Thank you for the answers! Adding configuration to the key of remember definitely works, but won't it then recompose every time
configuration
changes? (Opposed to recomposition only when the result of the calculation changes)
In this case configuration obviously doesn't change very often, but what about the theoretical case of some frequently updating value provided by another CompositionLocal?
s

Sean McQuillan [G]

06/27/2022, 8:10 PM
rememberUpdatedState should give you the object you're looking for in that case
that said, if you're doing that much in composition - very strongly consider
extract class
and move it to Kotlin
:thank-you: 1