ascii
08/30/2023, 9:51 AMascii
08/30/2023, 9:54 AM@Composable
fun ColumnScope.BannerAd(
adUnitId: String,
adLoaded: MutableState<Boolean>? = null,
viewUpdated: (AdView) -> Unit,
) = if (LocalInspectionMode.current) {
Text("AdView")
} else AndroidView(factory = {
AdView(it).apply {
…init…
if (adLoaded != null) adListener = object : AdListener() {
override fun onAdFailedToLoad(error: LoadAdError) { adLoaded.value = false }
override fun onAdLoaded() { adLoaded.value = true }
}
}
}, if (adLoaded?.value == true) Modifier.something() else Modifier, viewUpdated)
I could pass adListener
and Modifier
from the parent composable itself, which bypasses the need to pass a MutableState
to this child, but that introduces the bigger question in more complicated situations: what do I do if it's not always possible to move things out? Do I forego this separate child composable entirely, and put everything in the parent composable? Or do I deconstruct MutableState and pass value/setter separately?
From what I've seen with benchmarks and Layout Inspector, there aren't any performance issues or unnecessary recompositions when I pass a MutableState.Stylianos Gakis
08/30/2023, 10:03 AMT
or () -> T
)
Also pass down a way for the child to change the state by passing a (T) -> Unit
if the child also needs to change the value.
Never pass State<T>
and especially not MutableState<T>
down. For the first just because () -> T
is better, and for the second don’t do it because you introduce a very hard to reason about flow of where you state changes.ascii
08/30/2023, 12:33 PM