<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Edgar  Harutyunyan on Medium]]></title>
        <description><![CDATA[Stories by Edgar  Harutyunyan on Medium]]></description>
        <link>https://medium.com/@edgarharutyunyan_21906?source=rss-57944933d7cd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TX8Q8Y3vCXHVQRp7KfxRCg.jpeg</url>
            <title>Stories by Edgar  Harutyunyan on Medium</title>
            <link>https://medium.com/@edgarharutyunyan_21906?source=rss-57944933d7cd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 14:07:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@edgarharutyunyan_21906/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Mastering CompositionLocal in Jetpack Compose -Adaptive Spacing for All Screen Size]]></title>
            <link>https://medium.com/@edgarharutyunyan_21906/mastering-compositionlocal-in-jetpack-compose-adaptive-spacing-for-all-screen-size-0fc22de8edc8?source=rss-57944933d7cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/0fc22de8edc8</guid>
            <dc:creator><![CDATA[Edgar  Harutyunyan]]></dc:creator>
            <pubDate>Wed, 13 Aug 2025 06:43:53 GMT</pubDate>
            <atom:updated>2025-08-13T06:43:53.642Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3V4OtyEX6_rHRTsTUupFvQ.png" /></figure><p>When working on UI in Jetpack Compose, we often face the challenge of providing consistent spacing, shapes, and colors across the app — while still adapting them for different screen sizes and densities.<br> Most articles about CompositionLocal cover only the basics, without explaining how to make these values dynamic depending on screen characteristics.</p><p><strong>In this post, we’ll:<br></strong>1. Explore what CompositionLocal is and why you should use it.<br>2. Create an adaptive spacing system based on screen density.<br>3. Integrate it into a custom theme.<br>4. Use it in our UI.</p><h4>1. What is CompositionLocal?</h4><p>CompositionLocal is a powerful mechanism in Jetpack Compose that allows you to pass data down the composable tree <strong>without explicitly passing it through every function parameter</strong>.</p><p>Think of it like context in React or dependency injection, but designed for the declarative nature of Compose.</p><h4>🚀 Key Concepts</h4><h4>1.1. Implicit Value Propagation</h4><p>Rather than passing data manually, you define a value in a scope and access it anywhere inside that scope.</p><pre>val LocalAppColor = compositionLocalOf { Color.Magenta }<br><br>Box(<br>    modifier = Modifier<br>         .fillMaxWidth()<br>         .height(60.dp)<br>         .background(LocalAppColor.current) // getting color from CompositionLocal<br>    ) {<br>        Text(&quot;Header&quot;, modifier = Modifier.padding(16.dp), color = Color.White)<br>    }</pre><h4>1.2. Scoped Access</h4><p>Values are only available inside the CompositionLocalProvider where they are set, preventing accidental global leaks.</p><pre>val LocalUserName = compositionLocalOf { &quot;Guest&quot; }<br><br>@Composable<br>fun AppRoot() {<br>    Column(modifier = Modifier.fillMaxSize().padding(16.dp)) {<br>        <br>        CompositionLocalProvider(LocalUserName provides &quot;Alice&quot;) {<br>            UserProfile() // &quot;Alice&quot; <br>        }<br><br>        Spacer(Modifier.height(16.dp))<br><br>        CompositionLocalProvider(LocalUserName provides &quot;Bob&quot;) {<br>            UserProfile() // &quot;Bob&quot;<br>        }<br><br>        Spacer(Modifier.height(16.dp))<br><br>        UserProfile() // &quot;Guest&quot;<br>    }<br>}</pre><h4>1.3. Recomposition Friendly</h4><p>If a CompositionLocal value changes, any composables using it automatically recompose.</p><h4>1.4. No Global State</h4><p>Although it feels like shared context, CompositionLocal is tied to the composable tree, making it safe for multi-window or preview usage.</p><h4><strong>2. Creating Adaptive Spacing with CompositionLocal</strong></h4><p>We’ll build a Spacing interface and different implementations for various screen densities.</p><pre>interface Spacing {<br>    val default: Dp<br>    val extraSmall: Dp<br>    val small: Dp<br>    val medium: Dp<br>    val large: Dp<br>}<br><br>data class SpacingDefault(<br>    override val default: Dp = 8.dp,<br>    override val extraSmall: Dp = 4.dp,<br>    override val small: Dp = 8.dp,<br>    override val medium: Dp = 16.dp,<br>    override val large: Dp = 32.dp,<br>) : Spacing<br><br>data class SpacingXHDPI(<br>    override val default: Dp = 8.dp,<br>    override val extraSmall: Dp = 4.dp,<br>    override val small: Dp = 8.dp,<br>    override val medium: Dp = 16.dp,<br>    override val large: Dp = 32.dp,<br>) : Spacing<br><br>data class SpacingXXHDPI(<br>   override val default: Dp = 8.dp,<br>    override val extraSmall: Dp = 6.dp,<br>    override val small: Dp = 10.dp,<br>    override val medium: Dp = 18.dp,<br>    override val large: Dp = 36.dp,<br>) : Spacing</pre><h4>3. Handling Screen Density</h4><pre>enum class ScreenDensityEnum(val range: IntRange) {<br>    LDPI(0..120),        // ~120 dpi<br>    MDPI(121..160),      // ~160 dpi <br>    HDPI(161..240),      // ~240 dpi<br>    XHDPI(241..320),     // ~320 dpi<br>    XXHDPI(321..480),    // ~480 dpi<br>    XXXHDPI(481..640),   // ~640 dpi<br>    EXTRA_HIGH(641..Int.MAX_VALUE); <br><br>    operator fun get(value: Int) = entries.find {value in it.range} ?: MDPI<br>}</pre><h4>4. Providing Spacing via CompositionLocal</h4><pre>typealias Theme = MaterialTheme // optional <br><br>val Theme.spacing: Spacing<br>    @Composable<br>    @ReadOnlyComposable<br>    get() = LocalSpacing.current<br><br>val LocalSpacing = compositionLocalOf&lt;Spacing&gt; {<br>    error(&quot;no spacing provided&quot;)<br>}<br><br>@Composable<br>fun provideScreenSpacing(): Spacing {<br>    return when (ScreenDensityEnum[LocalConfiguration.current.densityDpi]) {<br>        ScreenDensityEnum.XHdpi -&gt; SpacingXHDPI()<br>        ScreenDensityEnum.XXHdpi -&gt; SpacingXXHDPI()<br>        else -&gt; SpacingDefault()<br>    }<br>}</pre><h4>5. Integrating into Your Theme</h4><pre>@Composable<br>fun MyApplicationTheme(<br>    content: @Composable () -&gt; Unit<br>) {<br>    val colorScheme = DarkColorScheme<br>    val spacing = provideScreenSpacing()<br><br>    CompositionLocalProvider(<br>        LocalSpacing provides spacing,<br>    ) {<br>        MaterialTheme(<br>            colorScheme = colorScheme,<br>            typography = Typography,<br>            content = content<br>        )<br>    }<br>}</pre><h4>6. Using It in Screens</h4><pre>@Composable<br>fun MyScreen() {<br>    Column(<br>        verticalArrangement = Arrangement.SpaceBetween,<br>        horizontalAlignment = Alignment.Start,<br>        modifier = Modifier<br>            .fillMaxSize()<br>            .padding(Theme.spacing.medium) // geting from theme<br>            .background(MaterialTheme.colorScheme.background)<br>    ) {<br>        Text(<br>            text = stringResource(id = R.string.global_whats_your_phone_number),<br>            style = MaterialTheme.typography.displaySmall.copy(<br>                fontWeight = FontWeight(700),<br>                color = MaterialTheme.colorScheme.onPrimary<br>            )<br>        )<br>    }<br>}</pre><h4>7. Why This Approach Works</h4><p>✅ <strong>No manual parameter passing</strong> — spacing is available anywhere inside your theme.<br> ✅ <strong>Adaptable UI</strong> — different screen densities get different spacing.<br> ✅ <strong>Composable-safe</strong> — values live within the composition tree, not global state.<br> ✅ <strong>Scalable</strong> — the same approach can be applied to shapes, colors, and typography.</p><h4>Why Not Just Use Dimen Resources?</h4><p>You might be wondering:<br> <em>“Why go through the trouble of creating a </em><em>Spacing </em><em>CompositionLocal when I could simply define spacing in </em><em>dimens.xml and call it a day?&quot;</em></p><p>Here’s why CompositionLocal can be a better choice in many modern Compose projects:</p><h3>1. Runtime Adaptation</h3><p>dimens.xml values are <strong>static</strong> — they are determined at compile time, and you can only have multiple versions by providing alternative resource files for specific swXXXdp or density qualifiers.</p><p>With CompositionLocal, you can:</p><ul><li>Dynamically calculate spacing at <strong>runtime</strong> based on LocalConfiguration (e.g., densityDpi or screen width).</li><li>Easily update spacing on the fly — even after the app is running (e.g., in settings or for accessibility purposes).</li></ul><h4>2. One Source of Truth Inside Compose</h4><p>When you use Spacing via CompositionLocal, it becomes part of your <strong>Compose theme</strong>, just like colorScheme or typography.<br> This means:</p><ul><li>Consistent access through MaterialTheme or a similar interface (Theme.spacing.medium).</li><li>No need to remember resource IDs or context calls.</li><li>No dependency on Resources or Context.</li></ul><h4>3. Better Testability</h4><p>Testing CompositionLocal values is easier in Compose previews and unit tests:</p><ul><li>You can wrap any composable with a custom CompositionLocalProvider to inject specific spacing values.</li><li>No need to load XML resources in tests.</li></ul><h4>4. Scoped Customization</h4><p>CompositionLocal allows <strong>per-screen or per-section spacing</strong>.<br> For example, you might have:</p><pre>CompositionLocalProvider(LocalSpacing provides CompactSpacing()) {<br>    CompactScreenContent()<br>}</pre><p>while keeping the rest of the app with DefaultSpacing.<br> Doing this with dimens resources would require a lot more setup and separate layouts.</p><h4>5. Seamless Multi-Platform Support</h4><p>If your Compose code targets multiple platforms (Android, Desktop, Web), XML-based dimens simply don’t exist outside Android.<br>CompositionLocal works everywhere.</p><h4><strong>Thanks for reading this topic!</strong></h4><p>If you found this helpful, feel free to share it with your fellow developers and leave a comment — I’d love to hear how you use CompositionLocal in your projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0fc22de8edc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>