Ricardo C.
10/12/2023, 3:27 PMModifier.composed + Modifier.then and I’m not totally sure why. I’ll explain more in 🧵Ricardo C.
10/12/2023, 3:28 PMfun Modifier.impression(
id: String,
): Modifier = composed {
Logger.v(tag = "ImpressionTracking") { "Creating modifier($id)" }
LaunchedEffect(key1 = id) {
Logger.v(tag = "ImpressionTracking") { "Launching effect($id)" }
}
this
}
fun Modifier.placeholderBackground(): Modifier =
this then background(Color(0xFF272727))
Example usage (my case is actually more complex but I think this is the minimum case):
Box (
modifier = Modifier
.impression("1")
.placeholderBackground()
)
That LaunchedEffect gets launched multiple times on recomposition. If I remove then from placeholderBackground :
fun Modifier.placeholderBackground(): Modifier =
this.background(Color(0xFF272727))
Then it only gets launched once.
It seems composed is not keeping state. I found this issue https://issuetracker.google.com/issues/270963071, but my case is with then on other modifiers. In the end it can possibly be the same issue. But this seems like a footgun that is not obvious at all.Ricardo C.
10/12/2023, 3:41 PMthen it duplicates the modifiers that were before into two different paths and ends up materialising composed twice, If I have more modifiers with then , it creates more paths and more composed materialisations, one “state” for each possible path on the tree.
And why does removing then solve it, when predefined modifiers also use it?efemoney
10/12/2023, 4:22 PMfun Modifier.placeholderBackground(): Modifier =
this then Modifier.background(...)
OR just
fun Modifier.placeholderBackground(): Modifier =
this.background(...)
It should be clear what the issue now is but if not:
The modifier extensions are shortcuts for chaining the this modifier with some other modifier so your old code actually did
this then (this.background(...))
which is basically
this then (this.then(BackgroundModifier(...)))efemoney
10/12/2023, 4:29 PMthis then Modifier.background(...)
work? …
Look at the source of Modifier ’s companion object is which is the empty Modifier , you can see that its then method, short circuits to the other modifierRicardo C.
10/12/2023, 4:30 PMRicardo C.
10/12/2023, 4:30 PMefemoney
10/12/2023, 4:32 PMRicardo C.
10/12/2023, 4:33 PMcomposed , which now I see is not the case.Ricardo C.
10/12/2023, 4:34 PMefemoney
10/12/2023, 4:34 PM