One Off the Slack: Why Is It Called "CompositionLocal"?

Scott Kruse asked an innocuous question:

Is anyone using dependency injection / oop for theming in compose? I see a lot of top level declaration in samples / material documentation

Colton Idle offered an alternative, in the form of CompositionLocal:

I think themes end up being one of those cases where Composition Locals (better known as Globals IMO) make sense to use instead of having to pass them down absolutely everywhere.

Colton’s use of “global” as a descriptor, though, kicked off responses from an all-star cast.

First up, Google’s Romain Guy:

Well they are local to a composition. They’re not true global values because of that. They’re scoped globals if you prefer

Colton then got to the heart of the problem, which is the confusing name:

I still don’t really understand the name composition locals. Isn’t any variable defined in a composable a composition local?

Jake Wharton offered an explanation:

a variable defined inside a @Composable is more like a recomposition local as its lifetime is tied to a single recomposition. Composition locals survive for the lifetime of the composition object across multiple recompositions

Well… kinda. It’s mostly that. You probably won’t harm yourself with that mental model, but there’s also more nuance since they’re hierarchical and can exist at different points in the tree.

Technically the composition owns the tree and therefore holds these composition locals, but since they can be installed at various points of the composable hierarchy installing a composition local does not mean it’s visible to 100% of the composables in that composition

A name which is fully accurate would probably be like 100 characters long and “composition local” is Close Enough™

Google’s Zach Klippenstein then got to the origins of the name:

CompositionLocal is also meant to pattern match to ThreadLocal. Just like TLs, CLs can have different values depending on where they’re read.


Read the original thread in the kotlinlang Slack workspace. Not a member? Join that Slack workspace here!