I would like to observe how the use of staticCompositionLocalOf
causes “the entirety of the content lambda of the CompositionLocalProvider
to be recomposed” as per the androids.compose.runtime
documentation:
Unlike
compositionLocalOf
, reads of astaticCompositionLocalOf
are not tracked by the composer and changing the value provided in theCompositionLocalProvider
call will cause the entirety of the content to be recomposed instead of just the places where in the composition the local value is used.
Running the attached code, I expected the Text
composable in both setContent
and in the Node
composable, and the Node
composable itself, to recompose when I click the Button
. However Android Studio’s Layer Inspector shows that only the Leaf
and the Text
composable in Leaf
were recomposed. As the attached screenshots show, changing staticCompositionLocalOf
on line 2 of the code to compositionLocalOf
resulted in the same recompositions.
data class Counter (var count: MutableState<Int> = mutableStateOf(0))
val LocalCounter = staticCompositionLocalOf<Counter> {
error("CompositionLocal LocalCounter not provided")
}
class MainActivity : ComponentActivity() {
private var counter = Counter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
CompositionLocalProvider(LocalCounter provides counter) {
Column {
Text("setContent ${LocalCounter}")
Node()
Button(content = { Text("+1") },
onClick = { counter.count.value += 1 }
)
}
}
}
}
}
@Composable
fun Node() {
Text("Node")
Leaf()
}
@Composable
fun Leaf() {
val counter = LocalCounter.current
Text("Leaf count: ${counter.count.value}")
}
I’ve run the code using Android Studio Jellyfish Patch 1 with Pixel 8 API 34 emulator, Android Studio Koala Canary 2 with Pixel 8 API VanillaIceCream emulator and physical Pixel 4a running API 33. All with Kotlin 1.9.24 and all with the same recompositions.
Related questions on stackoverflow, and the web at large, mostly asked about the usage of CompositionLocal
, such as How and when exactly CompositionLocal sets values implicitly? or /a/77496284, or about the conceptual difference between staticCompositionLocalOf
and compositionLocalOf
, which the official documentation explains. I couldn’t find any example code showing how the difference between these two can be shown.
Any example to show recomposition of composable that do not use the value provided, but due solely to the use of staticCompositionLocalOf
, would be much appreciated!