Compose CompositionLocalProvider
CompositionLocalProvider
is useful for sharing objects between composables without passing them as function parameters. Objects are stored in the composer and are available in the current tree that CompositionLocalProvider
wraps.
Compose offers providing data in static and observable manner, compositionLocalOf
maintains a mutable state of the provided object and forces recomposition where the provided value is read. On the other hand, staticCompositionalLocalOf
doesn’t observe changes in the object and will not trigger recomposition where the provided value is read.
Static
staticCompositionalLocalOf
can be used when we are sure that the object will most likely not change, practically immutable. staticCompositionalLocalOf
is efficient when used for values that are stored once and we want to make sure that updates to it do not have side effects.
Initially, the value for our LocalActivityIntent
is not provided and calling it prior it will force the default value factory that is called lazily throw and error.
We have to provide the value before it is used any where in our composables in the scope of the CompositionLocalProvider
.
Non-static
Objects provided with compositionLocalOf
can be easily misused and tracking the unnecessary recompositions is hard.
Updating the state of the Shape
object our LocalShape
will trigger recomposition where the value is read, but it can be done from anywhere because of the CompositionLocalProvider
. If we would have used the Shape
as parameter in the composables then we are in control when and where the object mutates.