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

xoangon

10/20/2023, 3:15 PM
Hi there mates! QQ about `CompositionLocal`s
We're using `CompositionLocal`s to set our app theme. Our app is using both Views and Compose and we're using
AbstractComposeView
in a lot of places, thus having more than one call to
setContent
. The thing is, if we forget to set the `CompositionLocal`s in any of those, we end up with a crash at runtime with a stack trace that's way far from explicit (full stack trace in this Google Issue Tracker report) I'd like to hook into any call to
setContent
and provide a meaningful error if those implicit dependencies are not provided. Is there a way to do this? If that's not feasible, I may consider some type of lint
s

Stylianos Gakis

10/20/2023, 3:53 PM
What you get by default from a CL is defined by you right? You could definitely have something like
Copy code
internal val Foo = staticCompositionLocalOf<Foo> {
  error("Foo not provided")
}
Would that be sufficient for you here?
x

xoangon

10/20/2023, 4:37 PM
That seems to be what I was looking for! On my way to test that out
s

Stylianos Gakis

10/20/2023, 4:41 PM
You could also consider not crashing in production but providing a sane default (as material3 color scheme does with light color scheme for example) but still log a high severity warning.
x

xoangon

10/20/2023, 4:55 PM
The snippet above is what I was looking for, thanks!
I used to do super-defensive programming with no errors at runtime at my previous company and were I am right now we do offensive programming with development under feature-flag. I was a bit shocked at first, but by providing meaningful errors and having an easy roll-back setup, I'm amazed by the time saved! Opposite to what I was expecting, our app ends up being more robust as we realise early when something's not working well instead of having a ton of users falling in undesired weird states with missing information
s

Stylianos Gakis

10/20/2023, 5:01 PM
Yep, as long as you got an easy way to roll back that is 😅
x

xoangon

10/20/2023, 5:02 PM
Yup, it would be crazy without that 🤣
m

myanmarking

10/21/2023, 8:57 PM
If it is a developer error, crash always. Going otherwise is making it worst
2 Views