https://kotlinlang.org logo
#compose
Title
# compose
l

lilypuchi

05/31/2022, 2:16 PM
Can someone explain why
Copy code
LocalConfiguration.current
line exists in
calculateWindowSizeClass(activity: Activity)
? Am I wrong in thinking that it does nothing here? 🤔 https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/[…]ndroidWindowSizeClass.android.kt;l=37?q=calculateWindowSi&sq=
f

Filip Wiesner

05/31/2022, 2:18 PM
I think it's explained in the comment above:
Copy code
// Observe view configuration changes and recalculate the size class on each change. We can't
// use Activity#onConfigurationChanged as this will sometimes fail to be called on different
// API levels, hence why this function needs to be @Composable so we can observe the
// ComposeView's configuration changes.
🙌 1
l

lilypuchi

05/31/2022, 2:19 PM
Oh so just calling
LocalConfiguration.current
triggers Recomposition? 🤔
f

Filip Wiesner

05/31/2022, 2:20 PM
I believe so
👍 1
l

Louis Pullen-Freilich [G]

05/31/2022, 2:21 PM
Yes, reading this will cause this to recompose when
LocalConfiguration.current
changes. And
LocalConfiguration.current
changes whenever
onConfigurationChanged
is called on the
ComposeView
. So essentially this will recompose everytime
onConfigurationChanged
is called on the view
🙌 1
n

nitrog42

05/31/2022, 2:32 PM
the same mecanism is used for stringResource() btw !
Copy code
@Composable
@ReadOnlyComposable
private fun resources(): Resources {
    LocalConfiguration.current
    return LocalContext.current.resources
}

@Composable
@ReadOnlyComposable
fun stringResource(@StringRes id: Int): String {
    val resources = resources()
    return resources.getString(id)
}
🙌 1
l

lilypuchi

05/31/2022, 2:33 PM
Oh you’re right. Well it’s a TIL for me 😃 Thanks all!
🎉 2
h

hfhbd

05/31/2022, 2:43 PM
But why does
resources
need to call
LocalConfiguration.current
twice?
l

lilypuchi

05/31/2022, 2:44 PM
Even I misread it the first time. The later one is
LocalContext
not config blob sweat smile
h

hfhbd

05/31/2022, 2:44 PM
Oh 🤦‍♂️ Thanks 😄
🙌 2
l

Landry Norris

05/31/2022, 3:51 PM
This appears generalizable to any state variable. In one of my projects, I had a really weird edge case where I needed to recalculate something whenever a recomposition occurred, and I needed recomposition to occur when a variable changed, so I just had a line that read the variable with a comment explaining the mechanism and why the variable couldn’t be removed.
57 Views