<?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 Gal machluf on Medium]]></title>
        <description><![CDATA[Stories by Gal machluf on Medium]]></description>
        <link>https://medium.com/@galmc1986?source=rss-4fcfe1906a46------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HJ3jGBwFd9LbftekwMFwtQ@2x.jpeg</url>
            <title>Stories by Gal machluf on Medium</title>
            <link>https://medium.com/@galmc1986?source=rss-4fcfe1906a46------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 16:49:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@galmc1986/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[From Individual AI Usage to Team-Wide Agentic Workflows]]></title>
            <link>https://medium.com/@galmc1986/from-individual-ai-usage-to-team-wide-agentic-workflows-2fded7c4afa5?source=rss-4fcfe1906a46------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fded7c4afa5</guid>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[engineering-leadership]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Gal machluf]]></dc:creator>
            <pubDate>Sun, 06 Sep 2026 14:02:56 GMT</pubDate>
            <atom:updated>2026-09-06T14:02:56.673Z</atom:updated>
            <content:encoded><![CDATA[<p>How we started turning AI from a personal productivity tool into a shared engineering capability</p><p>AI adoption in engineering often starts the same way.</p><p>One engineer uses AI to debug an issue. Another uses it to review code. Someone else creates a useful prompt for writing tests or understanding an unfamiliar part of the codebase.</p><p>All of these can save time.</p><p>But there is a problem: the knowledge usually stays with the individual.</p><p>The same problems are solved again and again. Good prompts get lost in chat history. Every engineer develops their own way of providing context. And when someone discovers an effective workflow, the rest of the team may never know about it.</p><p>At some point, I started thinking about a different question:</p><p>What happens when we stop treating AI as an individual tool and start treating it as part of the engineering system?</p><p>That question led us toward a more structured approach to AI-assisted development and agentic workflows.</p><p>Prompts are useful. Workflows are more powerful.</p><p>A good prompt can make an engineer faster at a specific task.</p><p>But software development rarely consists of isolated tasks.</p><p>Consider something as simple as implementing a feature.</p><p>An engineer may need to understand an existing architecture, locate the relevant code, inspect similar implementations, understand team conventions, implement the change, write tests, review potential edge cases, update documentation and verify that the solution follows architectural guidelines.</p><p>A single prompt does not really represent that process.</p><p>A workflow does.</p><p>This is where agentic approaches started becoming much more interesting to me.</p><p>Instead of repeatedly explaining the same context and instructions, we can build reusable workflows that understand how we expect engineering tasks to be performed.</p><p>The goal isn’t to let an agent blindly write code.</p><p>The goal is to encode more of our engineering context, standards and decision-making process into something reusable.</p><p>From personal knowledge to shared engineering knowledge</p><p>One of the biggest changes we made was creating a department-wide repository for reusable AI skills and workflows.</p><p>The idea was relatively simple:</p><p>If an engineer discovers a useful AI-assisted process, it shouldn’t remain in their personal chat history.</p><p>It should be possible for someone else to use it, improve it and build on top of it.</p><p>The repository became a place where we could capture things such as:</p><ul><li>Reusable AI skills for common engineering tasks</li><li>• Agentic workflows</li><li>• Development and architectural conventions</li><li>• Structured instructions for recurring tasks</li><li>• Shared context that helps AI understand how we build software</li><li>• Lessons learned from workflows that worked – and ones that didn’t</li></ul><p>This changes the role of AI significantly.</p><p>Instead of every engineer starting from zero, the organization begins accumulating AI-enabled engineering knowledge.</p><p>And that knowledge can improve over time.</p><p>The repository isn’t the important part</p><p>Git repositories are easy to create.</p><p>The interesting part is the behavior around them.</p><p>A shared repository creates an opportunity to treat AI workflows similarly to other engineering assets.</p><p>They can be reviewed.</p><p>They can evolve.</p><p>They can be versioned.</p><p>Someone can improve a workflow after discovering an edge case.</p><p>A team can adapt a generic skill to its own architecture.</p><p>And instead of ten engineers independently figuring out how to solve the same problem with AI, one good solution can become a starting point for everyone.</p><p>That is where I believe a much larger productivity opportunity exists.</p><p>Not necessarily in making one engineer dramatically faster, but in reducing duplicated thinking across an engineering organization.</p><p>AI should understand more than the task</p><p>One lesson that became increasingly clear is that AI becomes much more useful when it understands the environment in which the task exists.</p><p>“Implement this feature” isn’t enough.</p><p>The useful context often includes questions such as:</p><p>What architecture do we use?</p><p>Where should business logic live?</p><p>How do we structure state?</p><p>What testing approach do we expect?</p><p>Which patterns should be avoided?</p><p>What does a good pull request look like in this codebase?</p><p>What trade-offs matter to this team?</p><p>These are things experienced engineers gradually learn by working in an organization.</p><p>A good AI-enabled workflow should capture some of that knowledge as well.</p><p>This is one of the reasons I see reusable skills as more interesting than simply maintaining a collection of prompts.</p><p>A prompt usually describes what you want.</p><p>A skill can also describe how we work.</p><p>Agentic doesn’t mean autonomous</p><p>There is also an important misconception around agentic development.</p><p>The goal isn’t necessarily to remove the engineer from the process.</p><p>For many engineering tasks, I don’t think that would even be desirable.</p><p>Instead, I see agents as a way to automate parts of the engineering loop:</p><p>Understand → Investigate → Propose → Implement → Validate → Review</p><p>The engineer still provides intent, judgment and accountability.</p><p>But more of the repetitive exploration and mechanical work can happen automatically.</p><p>That allows the engineer to spend more time on the parts where human judgment matters most: architecture, product trade-offs, edge cases and deciding whether the proposed solution is actually the right one.</p><p>The leadership challenge is different</p><p>There is another side to this that I find especially interesting as an engineering leader.</p><p>Introducing AI into an engineering organization isn’t primarily a tooling problem.</p><p>It’s an engineering-practices problem.</p><p>Giving everyone access to an AI coding tool is easy.</p><p>Creating a culture where useful workflows are shared, reviewed and improved is harder.</p><p>Teams need to learn what should be automated, where human review is essential, how context should be provided, and how to avoid turning generated code into additional technical debt.</p><p>This means AI adoption needs many of the same things we already expect from good engineering:</p><p>Standards, ownership, feedback loops, documentation and continuous improvement.</p><p>Where I think this is going</p><p>I don’t think the biggest change in software engineering will come from engineers simply typing fewer lines of code.</p><p>I think it will come from engineering organizations gradually turning parts of their accumulated knowledge into executable workflows.</p><p>Today, a lot of engineering knowledge lives in people’s heads, documentation, Slack conversations, pull requests and tribal knowledge.</p><p>Agentic workflows give us another way to make some of that knowledge reusable.</p><p>We are still early in this transition, and there is plenty to learn.</p><p>But one principle has already become clear to me:</p><p>The real value of AI in engineering starts to compound when useful individual practices become shared organizational capabilities.</p><p>That is the transition I’m most interested in exploring next.</p><p>#AIEngineering #AgenticAI #EngineeringLeadership #DeveloperProductivity #SoftwareEngineering</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fded7c4afa5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Jetpack Compose Navigation 3: The Ultimate Guide ]]></title>
            <link>https://medium.com/@galmc1986/mastering-jetpack-compose-navigation-3-the-ultimate-guide-55a7ad4ab954?source=rss-4fcfe1906a46------2</link>
            <guid isPermaLink="false">https://medium.com/p/55a7ad4ab954</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Gal machluf]]></dc:creator>
            <pubDate>Sun, 30 Nov 2025 08:12:18 GMT</pubDate>
            <atom:updated>2025-11-30T08:12:18.669Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gh2B97jLwDk79l_EYDb2Ug.png" /></figure><p><em>Navigation just got a glow-up. Forget everything you knew about NavController.</em></p><p>If you’ve ever felt like wrestling an octopus while trying to manage navigation state in your Android app, congratulations — you’ve used Navigation 2. But fear not! Google has heard our collective screams and delivered <strong>Navigation 3</strong> (Nav3), a Compose-first navigation library that actually makes sense.</p><p>Announced at Google I/O 2025 and now <strong>stable as of November 2025</strong>, Nav3 is here to make your life easier. Let’s dive deep into mastering this beast!</p><h3>What is Navigation 3 and Why Should You Care? 🤔</h3><p>Navigation 3 is a completely new navigation library built from the ground up for Jetpack Compose. Unlike its predecessor (Nav2), which was designed back in 2018 when Compose was just a twinkle in Google’s eye, Nav3 embraces the declarative programming model as its foundation.</p><h3>The Old Pain Points (RIP Nav2 Problems)</h3><p>Remember these gems?</p><ul><li><strong>Back stack as a black box</strong>: You couldn’t directly observe or manipulate the back stack state. It was like trying to find your keys in a dark room.</li><li><strong>Single destination display</strong>: NavHost could only show one destination at a time. Tablets? What tablets?</li><li><strong>Two sources of truth</strong>: The library had its own internal state that could conflict with yours. Spoiler: chaos ensued.</li></ul><h3>Nav3’s Core Philosophy: You Own Everything</h3><p>Nav3 is built on three revolutionary principles:</p><ol><li><strong>You own the back stack</strong> — It’s literally just a list. Add items, remove items, done. 🎤💧</li><li><strong>Get out of your way</strong> — No more black boxes. Everything is open and extensible.</li><li><strong>Pick your building blocks</strong> — Combine smaller components to create exactly what you need.</li></ol><h3>Getting Started: Dependencies 📦</h3><p>First things first, let’s add the dependencies. Open your libs.versions.toml:</p><pre>[versions]<br>navigation3 = &quot;1.0.0&quot;<br>kotlinSerialization = &quot;2.1.21&quot;<br>kotlinxSerializationCore = &quot;1.8.1&quot;<br><br>[libraries]<br># Core Navigation 3 libraries<br>androidx-navigation3-runtime = { module = &quot;androidx.navigation3:navigation3-runtime&quot;, version.ref = &quot;navigation3&quot; }<br>androidx-navigation3-ui = { module = &quot;androidx.navigation3:navigation3-ui&quot;, version.ref = &quot;navigation3&quot; }<br><br># Optional: ViewModel support<br>androidx-lifecycle-viewmodel-navigation3 = { module = &quot;androidx.lifecycle:lifecycle-viewmodel-navigation3&quot;, version.ref = &quot;navigation3&quot; }<br><br># Serialization for persistent back stack<br>kotlinx-serialization-core = { module = &quot;org.jetbrains.kotlinx:kotlinx-serialization-core&quot;, version.ref = &quot;kotlinxSerializationCore&quot; }</pre><p>And in your build.gradle.kts:</p><pre>plugins {<br>    kotlin(&quot;plugin.serialization&quot;) version &quot;2.1.21&quot;<br>}</pre><pre>dependencies {<br>    implementation(libs.androidx.navigation3.runtime)<br>    implementation(libs.androidx.navigation3.ui)<br>    implementation(libs.kotlinx.serialization.core)<br>}</pre><p><em>Pro tip: The serialization plugin is essential if you want your back stack to survive process death. And trust me, you want that.</em></p><h3>The Fundamentals: Keys, BackStack, and NavDisplay 🔑</h3><p>Nav3’s architecture is beautifully simple. Let’s break it down:</p><h3>1. Define Your Keys (Destinations)</h3><p>Keys are how you identify your screens. They can be any type, but using @Serializable data classes/objects with NavKey interface is the recommended approach:</p><pre>import androidx.navigation3.runtime.NavKey<br>import kotlinx.serialization.Serializable<br><br>// Simple destination with no arguments<br>@Serializable<br>data object Home : NavKey<br><br>// Destination with parameters<br>@Serializable<br>data class ProductDetails(val productId: String) : NavKey<br><br>// Another destination with multiple parameters<br>@Serializable<br>data class UserProfile(val userId: Int, val userName: String) : NavKey<br><br>// Settings screen<br>@Serializable<br>data object Settings : NavKey</pre><p><em>Think of keys as the address to your screen. “Hey Nav3, take me to ProductDetails(id = ‘abc’)!” — and off you go.</em></p><h3>2. Create a Back Stack</h3><p>The back stack is literally a SnapshotStateList. Yes, that&#39;s it. A list.</p><pre>@Composable<br>fun MyApp() {<br>    // Option 1: Simple back stack (doesn&#39;t survive process death)<br>    val backStack = remember { mutableStateListOf&lt;Any&gt;(Home) }<br>    <br>    // Option 2: Persistent back stack (survives configuration changes AND process death)<br>    val backStack = rememberNavBackStack(Home)<br>    <br>    // Navigation is now as simple as:<br>    // Go forward: backStack.add(ProductDetails(&quot;123&quot;))<br>    // Go back: backStack.removeLastOrNull()<br>}</pre><p><em>That’s right. No </em><em>navController.navigate(). No route strings. No argument parsing. Just. A. List.</em></p><h3>3. Display with NavDisplay</h3><p>NavDisplay is the UI component that observes your back stack and renders the appropriate content:</p><pre>@Composable<br>fun MyApp() {<br>    val backStack = rememberNavBackStack(Home)<br>    <br>    NavDisplay(<br>        backStack = backStack,<br>        onBack = { backStack.removeLastOrNull() },<br>        entryProvider = entryProvider {<br>            entry&lt;Home&gt; {<br>                HomeScreen(<br>                    onNavigateToProduct = { productId -&gt;<br>                        backStack.add(ProductDetails(productId))<br>                    }<br>                )<br>            }<br>            entry&lt;ProductDetails&gt; { key -&gt;<br>                ProductScreen(<br>                    productId = key.productId,<br>                    onBack = { backStack.removeLastOrNull() }<br>                )<br>            }<br>            entry&lt;Settings&gt; {<br>                SettingsScreen()<br>            }<br>        }<br>    )<br>}</pre><p><em>Look ma, no NavController!</em> 🎉</p><h3>Complete Sample App: Coffee Shop ☕</h3><p>Let’s build a small but complete coffee ordering app to see Nav3 in action:</p><pre>import androidx.compose.foundation.layout.*<br>import androidx.compose.material3.*<br>import androidx.compose.runtime.*<br>import androidx.compose.ui.Alignment<br>import androidx.compose.ui.Modifier<br>import androidx.compose.ui.unit.dp<br>import androidx.navigation3.runtime.*<br>import androidx.navigation3.ui.NavDisplay<br>import kotlinx.serialization.Serializable<br><br>// ============================================<br>// STEP 1: Define your navigation keys<br>// ============================================<br><br>sealed interface CoffeeNavKey : NavKey<br><br>@Serializable<br>data object CoffeeMenu : CoffeeNavKey<br><br>@Serializable<br>data class CoffeeDetails(<br>    val coffeeId: String,<br>    val coffeeName: String,<br>    val price: Double<br>) : CoffeeNavKey<br><br>@Serializable<br>data class OrderConfirmation(<br>    val coffeeName: String,<br>    val quantity: Int,<br>    val totalPrice: Double<br>) : CoffeeNavKey<br><br>// ============================================<br>// STEP 2: Create the main navigation container<br>// ============================================<br><br>@Composable<br>fun CoffeeShopApp() {<br>    val backStack = rememberNavBackStack(CoffeeMenu)<br>    <br>    Scaffold { paddingValues -&gt;<br>        NavDisplay(<br>            modifier = Modifier.padding(paddingValues),<br>            backStack = backStack,<br>            onBack = { backStack.removeLastOrNull() },<br>            entryProvider = entryProvider {<br>                <br>                entry&lt;CoffeeMenu&gt; {<br>                    CoffeeMenuScreen(<br>                        onCoffeeSelected = { id, name, price -&gt;<br>                            backStack.add(CoffeeDetails(id, name, price))<br>                        }<br>                    )<br>                }<br>                <br>                entry&lt;CoffeeDetails&gt; { key -&gt;<br>                    CoffeeDetailsScreen(<br>                        coffeeName = key.coffeeName,<br>                        price = key.price,<br>                        onOrder = { quantity -&gt;<br>                            backStack.add(<br>                                OrderConfirmation(<br>                                    coffeeName = key.coffeeName,<br>                                    quantity = quantity,<br>                                    totalPrice = key.price * quantity<br>                                )<br>                            )<br>                        },<br>                        onBack = { backStack.removeLastOrNull() }<br>                    )<br>                }<br>                <br>                entry&lt;OrderConfirmation&gt; { key -&gt;<br>                    OrderConfirmationScreen(<br>                        coffeeName = key.coffeeName,<br>                        quantity = key.quantity,<br>                        totalPrice = key.totalPrice,<br>                        onBackToMenu = {<br>                            // Clear the back stack and go back to menu<br>                            backStack.clear()<br>                            backStack.add(CoffeeMenu)<br>                        }<br>                    )<br>                }<br>            }<br>        )<br>    }<br>}<br><br>// ============================================<br>// STEP 3: Create your screens<br>// ============================================<br><br>@Composable<br>fun CoffeeMenuScreen(<br>    onCoffeeSelected: (String, String, Double) -&gt; Unit<br>) {<br>    val coffees = listOf(<br>        Triple(&quot;1&quot;, &quot;Espresso&quot;, 3.50),<br>        Triple(&quot;2&quot;, &quot;Cappuccino&quot;, 4.50),<br>        Triple(&quot;3&quot;, &quot;Latte&quot;, 5.00),<br>        Triple(&quot;4&quot;, &quot;Americano&quot;, 3.00)<br>    )<br>    <br>    Column(<br>        modifier = Modifier<br>            .fillMaxSize()<br>            .padding(16.dp)<br>    ) {<br>        Text(<br>            text = &quot;☕ Coffee Menu&quot;,<br>            style = MaterialTheme.typography.headlineLarge<br>        )<br>        Spacer(modifier = Modifier.height(16.dp))<br>        <br>        coffees.forEach { (id, name, price) -&gt;<br>            Card(<br>                modifier = Modifier<br>                    .fillMaxWidth()<br>                    .padding(vertical = 8.dp),<br>                onClick = { onCoffeeSelected(id, name, price) }<br>            ) {<br>                Row(<br>                    modifier = Modifier<br>                        .fillMaxWidth()<br>                        .padding(16.dp),<br>                    horizontalArrangement = Arrangement.SpaceBetween<br>                ) {<br>                    Text(text = name, style = MaterialTheme.typography.titleMedium)<br>                    Text(text = &quot;$${&quot;%.2f&quot;.format(price)}&quot;)<br>                }<br>            }<br>        }<br>    }<br>}<br><br>@Composable<br>fun CoffeeDetailsScreen(<br>    coffeeName: String,<br>    price: Double,<br>    onOrder: (Int) -&gt; Unit,<br>    onBack: () -&gt; Unit<br>) {<br>    var quantity by remember { mutableIntStateOf(1) }<br>    <br>    Column(<br>        modifier = Modifier<br>            .fillMaxSize()<br>            .padding(16.dp),<br>        horizontalAlignment = Alignment.CenterHorizontally<br>    ) {<br>        Text(<br>            text = coffeeName,<br>            style = MaterialTheme.typography.headlineLarge<br>        )<br>        Spacer(modifier = Modifier.height(8.dp))<br>        Text(<br>            text = &quot;$${&quot;%.2f&quot;.format(price)} each&quot;,<br>            style = MaterialTheme.typography.titleMedium<br>        )<br>        Spacer(modifier = Modifier.height(32.dp))<br>        <br>        // Quantity selector<br>        Row(<br>            verticalAlignment = Alignment.CenterVertically,<br>            horizontalArrangement = Arrangement.spacedBy(16.dp)<br>        ) {<br>            Button(onClick = { if (quantity &gt; 1) quantity-- }) {<br>                Text(&quot;-&quot;)<br>            }<br>            Text(<br>                text = &quot;$quantity&quot;,<br>                style = MaterialTheme.typography.headlineMedium<br>            )<br>            Button(onClick = { quantity++ }) {<br>                Text(&quot;+&quot;)<br>            }<br>        }<br>        <br>        Spacer(modifier = Modifier.height(16.dp))<br>        Text(<br>            text = &quot;Total: $${&quot;%.2f&quot;.format(price * quantity)}&quot;,<br>            style = MaterialTheme.typography.titleLarge<br>        )<br>        <br>        Spacer(modifier = Modifier.weight(1f))<br>        <br>        Row(<br>            modifier = Modifier.fillMaxWidth(),<br>            horizontalArrangement = Arrangement.spacedBy(16.dp)<br>        ) {<br>            OutlinedButton(<br>                onClick = onBack,<br>                modifier = Modifier.weight(1f)<br>            ) {<br>                Text(&quot;Back&quot;)<br>            }<br>            Button(<br>                onClick = { onOrder(quantity) },<br>                modifier = Modifier.weight(1f)<br>            ) {<br>                Text(&quot;Order&quot;)<br>            }<br>        }<br>    }<br>}<br><br>@Composable<br>fun OrderConfirmationScreen(<br>    coffeeName: String,<br>    quantity: Int,<br>    totalPrice: Double,<br>    onBackToMenu: () -&gt; Unit<br>) {<br>    Column(<br>        modifier = Modifier<br>            .fillMaxSize()<br>            .padding(16.dp),<br>        horizontalAlignment = Alignment.CenterHorizontally,<br>        verticalArrangement = Arrangement.Center<br>    ) {<br>        Text(<br>            text = &quot;🎉&quot;,<br>            style = MaterialTheme.typography.displayLarge<br>        )<br>        Spacer(modifier = Modifier.height(16.dp))<br>        Text(<br>            text = &quot;Order Confirmed!&quot;,<br>            style = MaterialTheme.typography.headlineLarge<br>        )<br>        Spacer(modifier = Modifier.height(8.dp))<br>        Text(<br>            text = &quot;$quantity x $coffeeName&quot;,<br>            style = MaterialTheme.typography.titleLarge<br>        )<br>        Text(<br>            text = &quot;Total: $${&quot;%.2f&quot;.format(totalPrice)}&quot;,<br>            style = MaterialTheme.typography.titleMedium<br>        )<br>        Spacer(modifier = Modifier.height(32.dp))<br>        Button(onClick = onBackToMenu) {<br>            Text(&quot;Back to Menu&quot;)<br>        }<br>    }<br>}</pre><h3>Best Practices 🏆</h3><p>Based on the official documentation and community patterns, here are the best practices you should follow:</p><h3>1. Always Use Entry Decorators for State Management</h3><p>Entry decorators handle state preservation and ViewModel scoping. Don’t skip them!</p><pre>NavDisplay(<br>    backStack = backStack,<br>    onBack = { backStack.removeLastOrNull() },<br>    entryDecorators = listOf(<br>        // Handles state saving across configuration changes<br>        rememberSavedStateNavEntryDecorator(),<br>        // Scopes ViewModels to NavEntry lifecycle (not Activity!)<br>        rememberViewModelStoreNavEntryDecorator()<br>    ),<br>    entryProvider = entryProvider {<br>        entry&lt;Home&gt; {<br>            val viewModel: HomeViewModel = hiltViewModel() // Scoped to this entry!<br>            HomeScreen(viewModel)<br>        }<br>    }<br>)</pre><p><em>Note: As of recent versions, </em><em>rememberSceneSetupNavEntryDecorator() is included by default and no longer needs to be manually added.</em></p><h3>2. Use rememberNavBackStack for Persistence</h3><p>If you want your navigation state to survive process death (you definitely do), use rememberNavBackStack:</p><pre>// ✅ Good - Survives configuration changes AND process death<br>val backStack = rememberNavBackStack(Home)<br><br>// ⚠️ Okay for simple cases - Only survives recomposition<br>val backStack = remember { mutableStateListOf&lt;Any&gt;(Home) }</pre><h3>3. Implement NavKey for Type Safety</h3><p>Always implement NavKey interface and use @Serializable:</p><pre>@Serializable<br>data class UserProfile(val userId: String) : NavKey<br><br>// This enables:<br>// - Type-safe navigation<br>// - Automatic serialization for process death<br>// - Better tooling support</pre><h3>4. Centralize Navigation Logic in a ViewModel</h3><p>For larger apps, keep your back stack in a ViewModel:</p><pre>class NavigationViewModel : ViewModel() {<br>    private val _backStack = mutableStateListOf&lt;NavKey&gt;(Home)<br>    val backStack: SnapshotStateList&lt;NavKey&gt; = _backStack<br>    <br>    fun navigateTo(destination: NavKey) {<br>        _backStack.add(destination)<br>    }<br>    <br>    fun goBack(): Boolean {<br>        return if (_backStack.size &gt; 1) {<br>            _backStack.removeLastOrNull()<br>            true<br>        } else {<br>            false<br>        }<br>    }<br>    <br>    fun clearAndNavigateTo(destination: NavKey) {<br>        _backStack.clear()<br>        _backStack.add(destination)<br>    }<br>}</pre><h3>5. Use Metadata for Custom Per-Screen Behavior</h3><p>Need custom animations or data for specific screens? Use metadata:</p><pre>entry&lt;ProductDetails&gt;(<br>    metadata = NavDisplay.transitionSpec {<br>        slideInHorizontally { it } togetherWith slideOutHorizontally { -it }<br>    } + mapOf(&quot;requiresAuth&quot; to true)<br>) { key -&gt;<br>    ProductDetailsScreen(key.productId)<br>}</pre><h3>Custom Animations 🎬</h3><p>Nav3 provides beautiful built-in animations, but you can customize them too:</p><h3>Global Transitions</h3><pre>NavDisplay(<br>    backStack = backStack,<br>    onBack = { backStack.removeLastOrNull() },<br>    transitionSpec = {<br>        // Forward navigation animation<br>        fadeIn(tween(300)) togetherWith fadeOut(tween(300))<br>    },<br>    popTransitionSpec = {<br>        // Back navigation animation<br>        fadeIn(tween(300)) togetherWith fadeOut(tween(300))<br>    },<br>    entryProvider = entryProvider { /* ... */ }<br>)</pre><h3>Per-Screen Custom Animations</h3><pre>entry&lt;ScreenC&gt;(<br>    metadata = NavDisplay.transitionSpec {<br>        // Slide up when entering<br>        slideInVertically(<br>            initialOffsetY = { it },<br>            animationSpec = tween(500)<br>        ) togetherWith ExitTransition.KeepUntilTransitionsFinished<br>    } + NavDisplay.popTransitionSpec {<br>        // Slide down when exiting<br>        EnterTransition.None togetherWith slideOutVertically(<br>            targetOffsetY = { it },<br>            animationSpec = tween(500)<br>        )<br>    } + NavDisplay.predictivePopTransitionSpec {<br>        // Animation for predictive back gesture<br>        slideInHorizontally { -it / 4 } togetherWith slideOutHorizontally { it }<br>    }<br>) { /* Screen content */ }</pre><p><em>Predictive back gestures are supported out of the box. Your users will thank you.</em> 🙏</p><h3>Bottom Navigation Implementation 📱</h3><p>Here’s how to implement bottom navigation with separate back stacks per tab:</p><pre>@Serializable<br>sealed interface BottomNavKey : NavKey {<br>    @Serializable<br>    data object Home : BottomNavKey<br>    <br>    @Serializable<br>    data object Search : BottomNavKey<br>    <br>    @Serializable<br>    data object Profile : BottomNavKey<br>    <br>    companion object {<br>        val items = listOf(Home, Search, Profile)<br>    }<br>}<br><br>@Composable<br>fun MainScreen() {<br>    // Separate back stack for each tab<br>    val homeBackStack = rememberNavBackStack(BottomNavKey.Home)<br>    val searchBackStack = rememberNavBackStack(BottomNavKey.Search)<br>    val profileBackStack = rememberNavBackStack(BottomNavKey.Profile)<br>    <br>    var currentTab by rememberSaveable { mutableStateOf(BottomNavKey.Home) }<br>    <br>    val currentBackStack = when (currentTab) {<br>        BottomNavKey.Home -&gt; homeBackStack<br>        BottomNavKey.Search -&gt; searchBackStack<br>        BottomNavKey.Profile -&gt; profileBackStack<br>    }<br>    <br>    Scaffold(<br>        bottomBar = {<br>            NavigationBar {<br>                BottomNavKey.items.forEach { key -&gt;<br>                    NavigationBarItem(<br>                        selected = currentTab == key,<br>                        onClick = {<br>                            if (currentTab != key) {<br>                                currentTab = key<br>                            } else {<br>                                // Tap again to reset the tab<br>                                when (key) {<br>                                    BottomNavKey.Home -&gt; <br>                                        resetStack(homeBackStack)<br>                                    BottomNavKey.Search -&gt; <br>                                        resetStack(searchBackStack)<br>                                    BottomNavKey.Profile -&gt; <br>                                        resetStack(profileBackStack)<br>                                }<br>                            }<br>                        },<br>                        icon = { /* Your icon */ },<br>                        label = { Text(key.toString()) }<br>                    )<br>                }<br>            }<br>        }<br>    ) { paddingValues -&gt;<br>        NavDisplay(<br>            modifier = Modifier.padding(paddingValues),<br>            backStack = currentBackStack,<br>            onBack = { currentBackStack.removeLastOrNull() },<br>            entryDecorators = listOf(<br>                rememberSavedStateNavEntryDecorator(),<br>                rememberViewModelStoreNavEntryDecorator()<br>            ),<br>            entryProvider = entryProvider {<br>                entry&lt;BottomNavKey.Home&gt; { HomeScreen() }<br>                entry&lt;BottomNavKey.Search&gt; { SearchScreen() }<br>                entry&lt;BottomNavKey.Profile&gt; { ProfileScreen() }<br>                // Add nested destinations as needed<br>            }<br>        )<br>    }<br>}<br><br>private fun resetStack(backStack: NavBackStack) {<br>    if (backStack.size &gt; 1) {<br>        backStack.removeRange(1, backStack.size)<br>    }<br>}</pre><h3>Adaptive Layouts with Scenes 🖥️📱</h3><p>One of Nav3’s killer features is the ability to show multiple destinations simultaneously. Perfect for tablets and foldables!</p><pre>@OptIn(ExperimentalMaterial3AdaptiveApi::class)<br>@Composable<br>fun AdaptiveProductScreen() {<br>    val backStack = rememberNavBackStack(ProductList)<br>    <br>    // Use Material&#39;s list-detail strategy<br>    val listDetailStrategy = rememberListDetailSceneStrategy&lt;NavKey&gt;()<br>    <br>    NavDisplay(<br>        backStack = backStack,<br>        onBack = { backStack.removeLastOrNull() },<br>        sceneStrategy = listDetailStrategy,<br>        entryDecorators = listOf(<br>            rememberSavedStateNavEntryDecorator(),<br>            rememberViewModelStoreNavEntryDecorator()<br>        ),<br>        entryProvider = entryProvider {<br>            entry&lt;ProductList&gt;(<br>                metadata = ListDetailSceneStrategy.listPane(<br>                    detailPlaceholder = { <br>                        // Shown when no detail is selected (tablet)<br>                        Text(&quot;Select a product&quot;)<br>                    }<br>                )<br>            ) {<br>                ProductListScreen(<br>                    onProductClick = { productId -&gt;<br>                        backStack.add(ProductDetail(productId))<br>                    }<br>                )<br>            }<br>            <br>            entry&lt;ProductDetail&gt;(<br>                metadata = ListDetailSceneStrategy.detailPane()<br>            ) { key -&gt;<br>                ProductDetailScreen(productId = key.productId)<br>            }<br>        }<br>    )<br>}</pre><p><em>On phones: single pane navigation. On tablets: side-by-side list-detail. Automatic. Beautiful. Chef’s kiss.</em> 👨‍🍳💋</p><h3>Migration from Nav2: The Quick Guide 🔄</h3><p>If you’re coming from Nav2, here’s the TL;DR migration path:</p><p>Nav2 Nav3 NavController NavBackStack (just a list!) NavHost NavDisplay composable(&quot;route&quot;) entry&lt;Key&gt; navController.navigate(&quot;route&quot;) backStack.add(Key) navController.popBackStack() backStack.removeLastOrNull() Route strings Type-safe NavKey classes</p><h3>Migration Steps</h3><ol><li>Add Nav3 dependencies alongside Nav2</li><li>Create NavKey classes for your routes</li><li>Create a NavBackStack to hold your state</li><li>Replace NavHost with NavDisplay</li><li>Update navigation calls to use the back stack</li><li>Remove Nav2 dependencies when done</li></ol><p><em>Google even suggests using AI agents like Gemini to help with the migration. We live in the future!</em> 🤖</p><h3>Common Gotchas and Solutions ⚠️</h3><h3>Gotcha 1: Back Stack Not Surviving Configuration Changes</h3><p><strong>Problem</strong>: Using remember { mutableStateListOf() } doesn&#39;t survive process death.</p><p><strong>Solution</strong>: Use rememberNavBackStack() with NavKey implementing classes.</p><h3>Gotcha 2: ViewModels Scoped to Activity Instead of Screen</h3><p><strong>Problem</strong>: ViewModels persist across screen changes.</p><p><strong>Solution</strong>: Add rememberViewModelStoreNavEntryDecorator() to your decorators.</p><h3>Gotcha 3: State Lost on Tab Switch</h3><p><strong>Problem</strong>: Bottom navigation tabs lose their state.</p><p><strong>Solution</strong>: Use separate rememberNavBackStack() for each tab.</p><h3>Gotcha 4: Deep Links Not Working</h3><p><strong>Problem</strong>: Deep link support is still evolving in Nav3.</p><p><strong>Solution</strong>: Check the <a href="https://github.com/android/nav3-recipes">nav3-recipes repository</a> for the latest patterns. A deep links recipe is in development.</p><h3>Resources 📚</h3><ul><li><strong>Official Documentation</strong>: <a href="https://developer.android.com/guide/navigation/navigation-3">developer.android.com/guide/navigation/navigation-3</a></li><li><strong>Nav3 Recipes Repository</strong>: <a href="https://github.com/android/nav3-recipes">github.com/android/nav3-recipes</a></li><li><strong>Release Notes</strong>: <a href="https://developer.android.com/jetpack/androidx/releases/navigation3">developer.android.com/jetpack/androidx/releases/navigation3</a></li><li><strong>Migration Guide</strong>: <a href="https://developer.android.com/guide/navigation/navigation-3/migration-guide">developer.android.com/guide/navigation/navigation-3/migration-guide</a></li><li><strong>Announcing Blog Post</strong>: <a href="https://android-developers.googleblog.com/2025/05/announcing-jetpack-navigation-3-for-compose.html">android-developers.googleblog.com</a></li><li><strong>Nav3 is Stable Blog Post</strong>: <a href="https://android-developers.googleblog.com/2025/11/jetpack-navigation-3-is-stable.html">android-developers.googleblog.com</a></li></ul><h3>Conclusion 🎯</h3><p>Navigation 3 is a breath of fresh air for Android developers. By giving us complete control over the back stack and embracing Compose’s declarative nature, it removes so much of the friction we’ve experienced with navigation.</p><p>The key takeaways:</p><ol><li><strong>The back stack is yours - </strong>it’s just a list. Add, remove, observe. Done.</li><li><strong>Type safety is built-in - </strong>no more string routes and argument parsing nightmares.</li><li><strong>Adaptive layouts are first-class - </strong>tablets and foldables are no longer second-class citizens.</li><li><strong>Animations just work -</strong> including predictive back gestures.</li><li><strong>State management is explicit</strong> - decorators give you full control.</li></ol><p>Whether you’re starting a new project or migrating from Nav2, now is the perfect time to adopt Navigation 3. Your future self (and your team) will thank you.</p><p>Happy navigating! 🧭</p><p><em>If you found this article helpful, give it a clap (or 50 👏). Follow me for more Android content, and feel free to connect on LinkedIn!</em></p><p><em>Tags: #AndroidDevelopment #JetpackCompose #Navigation3 #Kotlin #MobileDevelopment #AndroidUI #GoogleIO2025</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55a7ad4ab954" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Kotlin Coroutines Best Practices That Will Save Your Sanity (And Your App)]]></title>
            <link>https://medium.com/@galmc1986/5-kotlin-coroutines-best-practices-that-will-save-your-sanity-and-your-app-9dabd3426316?source=rss-4fcfe1906a46------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dabd3426316</guid>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[Gal machluf]]></dc:creator>
            <pubDate>Tue, 25 Nov 2025 20:49:14 GMT</pubDate>
            <atom:updated>2025-11-25T20:49:14.786Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A no-nonsense guide to writing coroutines like a pro — with actual code examples and zero regrets</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ILbI8MP-DWqwaMhmicrn-Q.png" /></figure><p>You know that moment when your app crashes, and you trace it back to a rogue coroutine still running in the background like a zombie? Yeah, we’ve all been there. Kotlin coroutines are powerful, elegant, and wonderful — until they’re not.</p><p>After countless code reviews, debugging sessions, and “wait, why is this still running?” moments, I’ve compiled the essential best practices that separate production-ready coroutines from… well, production fires.</p><p>Let’s dive in! 🚀</p><h3>1. Never, Ever Use GlobalScope (Seriously, Just Don’t)</h3><h3>❌ DON’T DO THIS:</h3><pre>class UserRepository {<br>    fun loadUserData() {<br>        // 🔥 This is a memory leak waiting to happen<br>        GlobalScope.launch {<br>            val userData = fetchUserFromApi()<br>            updateCache(userData)<br>        }<br>    }<br>}</pre><h3>✅ DO THIS INSTEAD:</h3><pre>class UserRepository(<br>    private val externalScope: CoroutineScope<br>) {<br>    suspend fun loadUserData() {<br>        externalScope.launch {<br>            val userData = fetchUserFromApi()<br>            updateCache(userData)<br>        }<br>    }<br>}</pre><pre>// In your ViewModel<br>class UserViewModel : ViewModel() {<br>    private val repository = UserRepository(viewModelScope)<br>    <br>    fun loadUser() {<br>        viewModelScope.launch {<br>            repository.loadUserData()<br>        }<br>    }<br>}</pre><h3>Why This Matters:</h3><p>Using GlobalScope It&#39;s like throwing your laundry into a void and hoping it comes back clean. Spoiler alert: it doesn&#39;t. GlobalScope coroutines run for the entire application lifetime, creating several problems:</p><ol><li><strong>Memory Leaks</strong>: Your coroutine holds references to destroyed Activities/Fragments</li><li><strong>Untestable Code</strong>: You can’t control execution in tests</li><li><strong>No Structured Concurrency</strong>: Parent-child relationships are broken</li></ol><p>According to the <a href="https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-global-scope/">official Kotlin documentation</a>, GlobalScope is a “delicate API” that requires an explicit opt-in annotation. The docs literally say: “It is easy to accidentally create resource or memory leaks when GlobalScope is used.”</p><p><strong>Pro tip:</strong> On Android, use viewModelScope for ViewModels, lifecycleScope for Activities/Fragments. These scopes automatically cancel when their lifecycle ends. It&#39;s like having a responsible adult supervising your coroutines.</p><h3>2. Inject Your Dispatchers (Don’t Be That Person Who Hardcodes Everything)</h3><h3>❌ DON’T DO THIS:</h3><pre>class NewsRepository {<br>    suspend fun loadNews() = withContext(Dispatchers.Default) {<br>        // Hardcoded dispatcher = testing nightmare<br>        fetchNewsFromNetwork()<br>    }<br>}</pre><h3>✅ DO THIS INSTEAD:</h3><pre>class NewsRepository(<br>    private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO<br>) {<br>    suspend fun loadNews() = withContext(ioDispatcher) {<br>        fetchNewsFromNetwork()<br>    }<br>}</pre><pre>// In tests<br>@Test<br>fun testLoadNews() = runTest {<br>    val testDispatcher = StandardTestDispatcher()<br>    val repository = NewsRepository(testDispatcher)<br>    <br>    // Now you have full control over execution!<br>    repository.loadNews()<br>    testDispatcher.scheduler.advanceUntilIdle()<br>}</pre><h3>Why This Matters:</h3><p>Hardcoding dispatchers is like hardcoding your database connection strings. Sure, it works… until it doesn’t. The <a href="https://developer.android.com/kotlin/coroutines/coroutines-best-practices">Android best practices guide</a> explicitly states:</p><blockquote><em>“This dependency injection pattern makes testing easier as you can replace those dispatchers in unit and instrumentation tests with a test dispatcher to make your tests more deterministic.”</em></blockquote><p>When you inject dispatchers:</p><ul><li><strong>Tests become predictable</strong>: Control execution timing</li><li><strong>Code stays flexible</strong>: Easy to switch threading strategies</li><li><strong>Debugging gets easier</strong>: You can see which dispatcher is being used</li></ul><p>Think of it as dependency injection 101, but for threads. Your future self (debugging a flaky test at 2 AM) will thank you.</p><h3>3. Embrace Structured Concurrency (It’s Not Just a Buzzword)</h3><h3>❌ DON’T DO THIS:</h3><pre>suspend fun getUserData(): User {<br>    val userData = async { fetchUser() }.await()  // 🤦 Why though?<br>    return userData<br>}</pre><pre>// Or worse:<br>fun loadMultipleThings() {<br>    GlobalScope.launch { loadThing1() }<br>    GlobalScope.launch { loadThing2() }<br>    GlobalScope.launch { loadThing3() }<br>    // Who&#39;s managing these? Nobody knows!<br>}</pre><h3>✅ DO THIS INSTEAD:</h3><pre>// For simple suspend calls:<br>suspend fun getUserData(): User {<br>    return fetchUser()  // Just call it!<br>}</pre><pre>// For parallel execution with proper structure:<br>suspend fun loadAllData() = coroutineScope {<br>    val thing1 = async { loadThing1() }<br>    val thing2 = async { loadThing2() }<br>    val thing3 = async { loadThing3() }<br>    <br>    // All complete together, or fail together<br>    Triple(thing1.await(), thing2.await(), thing3.await())<br>}</pre><pre>// If you want independent failures:<br>suspend fun loadAllDataIndependently() = supervisorScope {<br>    val thing1 = async { loadThing1() }<br>    val thing2 = async { loadThing2() }<br>    <br>    // thing2 can fail without canceling thing1<br>    listOf(thing1, thing2).awaitAll()<br>}</pre><h3>Why This Matters:</h3><p>Structured concurrency is the whole point of Kotlin coroutines! According to the <a href="https://kotlinlang.org/docs/coroutines-basics.html">Kotlin coroutines basics guide</a>:</p><blockquote><em>“Coroutines form a tree hierarchy of parent and child tasks with linked lifecycles. A parent coroutine waits for its children to complete before it finishes. If the parent coroutine fails or gets canceled, all its child coroutines are recursively canceled too.”</em></blockquote><p>This means:</p><ul><li><strong>Predictable cancellation</strong>: Cancel parent → all children cancel</li><li><strong>Exception handling</strong>: Errors propagate properly</li><li><strong>Resource cleanup</strong>: No orphaned coroutines consuming resources</li></ul><p>The async { }.await() antipattern is especially funny (in a sad way). You&#39;re creating concurrency machinery for... sequential execution. As noted in <a href="https://kt.academy/article/cc-best-practices">Marcin Moskala&#39;s book</a>:</p><blockquote><em>“It makes no sense to define an asynchronous task with async if we want to await its completion without doing any operations during that time.”</em></blockquote><p>It’s like buying a sports car to drive in first gear. Just use a regular suspend function!</p><h3>4. Make Your Coroutines Cancellation-Cooperative</h3><h3>❌ DON’T DO THIS:</h3><pre>suspend fun processLargeDataset(data: List&lt;Item&gt;) = withContext(Dispatchers.Default) {<br>    // This will block cancellation!<br>    for (item in data) {<br>        processItem(item)  // Takes 100ms per item<br>        // If we have 10,000 items... we&#39;re here for a while<br>    }<br>}</pre><h3>✅ DO THIS INSTEAD:</h3><pre>suspend fun processLargeDataset(data: List&lt;Item&gt;) = withContext(Dispatchers.Default) {<br>    for (item in data) {<br>        ensureActive()  // Check if we&#39;ve been cancelled<br>        processItem(item)<br>        <br>        // Or use yield() to give other coroutines a chance<br>        yield()<br>    }<br>}</pre><pre>// Even better - use suspending functions:<br>suspend fun processLargeDataset(data: List&lt;Item&gt;) = withContext(Dispatchers.Default) {<br>    data.forEach { item -&gt;<br>        delay(1)  // This checks for cancellation automatically<br>        processItem(item)<br>    }<br>}</pre><h3>Why This Matters:</h3><p>Coroutine cancellation is <strong>cooperative</strong>, not forced. Your coroutine won’t magically stop when cancelled — it has to check. The <a href="https://developer.android.com/kotlin/coroutines/coroutines-best-practices">Android best practices</a> warn:</p><blockquote><em>“Cancellation in coroutines is cooperative, which means that when a coroutine’s Job is cancelled, the coroutine isn’t cancelled until it suspends or checks for cancellation.”</em></blockquote><p>When you have long-running loops or CPU-intensive work:</p><ul><li><strong>Call </strong><strong>ensureActive()</strong>: Throws CancellationException if cancelled</li><li><strong>Call </strong><strong>yield()</strong>: Gives up the thread and checks for cancellation</li><li><strong>Use suspending functions</strong>: They check cancellation automatically</li></ul><p>Not doing this is like ignoring your boss asking you to stop working on that feature. Sure, you can finish it, but… should you?</p><p>Real talk: I once had a coroutine processing 100,000 items that wouldn’t cancel. The user rotated their phone 50 times (as users do), spawning 50 uncancellable coroutines. The app felt like it was mining Bitcoin. Don’t be me.</p><h3>5. Choose the Right Dispatcher (Thread Wisely)</h3><h3>❌ DON’T DO THIS:</h3><pre>viewModelScope.launch {<br>    // 🔥 Doing heavy work on Main dispatcher<br>    val result = processHugeDataSet()  // Takes 5 seconds<br>    updateUI(result)<br>}</pre><pre>// Or opposite mistake:<br>viewModelScope.launch(Dispatchers.Default) {<br>    val data = fetchFromNetwork()<br>    // 💥 Trying to update UI from background thread<br>    textView.text = data  // CalledFromWrongThreadException!<br>}</pre><h3>✅ DO THIS INSTEAD:</h3><pre>viewModelScope.launch {<br>    // UI code runs on Main by default<br>    showLoading()<br>    <br>    // Switch to appropriate dispatcher for heavy work<br>    val result = withContext(Dispatchers.Default) {<br>        processHugeDataSet()  // CPU-intensive work<br>    }<br>    <br>    // Automatically back on Main<br>    hideLoading()<br>    updateUI(result)<br>}</pre><pre>// For network/database calls:<br>suspend fun loadUser(): User = withContext(Dispatchers.IO) {<br>    database.getUserById(userId)  // I/O work<br>}</pre><h3>Why This Matters:</h3><p>Dispatchers are your thread managers. Choose wrong, and you get ANRs or crashes. The <a href="https://kotlinlang.org/docs/coroutines-basics.html">Kotlin documentation</a> provides clear guidance:</p><ul><li><strong>Dispatchers.Main</strong>: UI updates, lightweight work</li><li><strong>Dispatchers.IO</strong>: Network calls, database operations, file I/O (up to 64 threads)</li><li><strong>Dispatchers.Default</strong>: CPU-intensive work, data processing (limited to CPU cores)</li></ul><p>Common dispatcher wisdom:</p><ul><li>Start on Main, switch contexts as needed</li><li>Use withContext for one-off context switches</li><li>Don’t switch back and forth unnecessarily (it has overhead!)</li></ul><p><strong>Pro tip from experience:</strong> Most modern libraries (Retrofit, Room) already use appropriate dispatchers internally. Don’t wrap their suspend functions in another withContext(Dispatchers.IO) — you&#39;re just adding overhead!</p><pre>// Room already runs on IO dispatcher<br>suspend fun getUser() = withContext(Dispatchers.IO) {  // ❌ Unnecessary!<br>    database.getUser()  // Already on IO internally<br>}</pre><pre>// Just do this:<br>suspend fun getUser() = database.getUser()  // ✅ Clean and efficient</pre><h3>Bonus: Quick Checklist for Code Reviews</h3><p>Before you push that PR, ask yourself:</p><ul><li>[ ] Am I using viewModelScope or lifecycleScope instead of GlobalScope?</li><li>[ ] Are my dispatchers injected (or using defaults intelligently)?</li><li>[ ] Do my long loops check for cancellation with ensureActive() or yield()?</li><li>[ ] Am I using coroutineScope or supervisorScope for structured concurrency?</li><li>[ ] Have I avoided the async{}.await() antipattern for sequential work?</li><li>[ ] Is my heavy computation on Dispatchers.Default and I/O on Dispatchers.IO?</li></ul><p>If you answered yes to all of these, congratulations! You’re writing coroutines like a senior engineer. 🎉</p><h3>Final Thoughts</h3><p>Kotlin coroutines are genuinely amazing when used correctly. They make asynchronous code readable, testable, and maintainable. But like any powerful tool, they require discipline and understanding.</p><p>The patterns in this article are battle-tested and backed by official guidance from JetBrains and Google. They’re not just theoretical best practices — they’re the difference between code that ships confidently and code that causes 3 AM production incidents.</p><p>Remember: coroutines aren’t magic. They’re structured concurrency with well-defined rules. Follow the rules, and your code will be beautiful. Break them, and… well, we’ve all seen callback hell. Coroutine hell is just as real, but with more subtle memory leaks.</p><p>Happy coding, and may your coroutines always cancel gracefully! 🚀</p><h3>Resources &amp; Further Reading</h3><p>Want to dive deeper? Check out these excellent resources:</p><ul><li><a href="https://kotlinlang.org/docs/coroutines-guide.html">Official Kotlin Coroutines Guide</a> — Start here</li><li><a href="https://developer.android.com/kotlin/coroutines/coroutines-best-practices">Best Practices for Coroutines in Android</a> — Android-specific guidance</li><li><a href="https://kotlinlang.org/docs/coroutines-basics.html">Kotlin Coroutines Basics</a> — Understanding fundamentals</li><li><a href="https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-global-scope/">GlobalScope Documentation</a> — Why it’s “delicate”</li><li><a href="https://kt.academy/article/cc-best-practices">Kotlin Coroutines Book by Marcin Moskala</a> — Deep dive into patterns</li></ul><p><em>Did this article save you from a memory leak? Found it helpful? Give it a clap! 👏</em></p><p><em>Have your own coroutine horror stories or tips? Drop them in the comments — we’re all learning together!</em></p><p><strong>About the Author:</strong> An Android developer who has made every coroutine mistake in this article (some twice) so you don’t have to. Currently writing clean, structured, properly-scoped coroutines… most of the time. 😅</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dabd3426316" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Best Practices for Jetpack Compose]]></title>
            <link>https://medium.com/@galmc1986/5-best-practices-for-jetpack-compose-c5f802d6b2ec?source=rss-4fcfe1906a46------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5f802d6b2ec</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Gal machluf]]></dc:creator>
            <pubDate>Mon, 24 Nov 2025 10:44:06 GMT</pubDate>
            <atom:updated>2025-11-24T10:44:06.780Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PoEHLR11PpfP6yafoIvHeg.png" /></figure><h3>Introduction</h3><p>Jetpack Compose has revolutionized Android UI development with its declarative approach. However, to build performant and maintainable applications, it’s crucial to follow established best practices. This guide presents five essential best practices backed by official Android documentation and expert recommendations, complete with practical do’s and don’ts.</p><h3>1. Cache Expensive Calculations with remember</h3><h3>The Problem</h3><p>Composable functions can execute very frequently — sometimes for every frame of an animation. Performing expensive calculations directly in the composable body can severely hurt performance.</p><h3>❌ DON’T: Perform calculations directly in composable body</h3><pre>@Composable<br>fun ContactList(<br>    contacts: List&lt;Contact&gt;,<br>    comparator: Comparator&lt;Contact&gt;,<br>    modifier: Modifier = Modifier<br>) {<br>    LazyColumn(modifier) {<br>        // BAD: This sorts the entire list on every recomposition<br>        items(contacts.sortedWith(comparator)) { contact -&gt;<br>            ContactRow(contact)<br>        }<br>    }<br>}</pre><p><strong>The issue:</strong> Every time ContactList recomposes (even when scrolling), the entire contact list is sorted again, causing unnecessary performance overhead.</p><h3>✅ DO: Use remember to cache calculations</h3><pre>@Composable<br>fun ContactList(<br>    contacts: List&lt;Contact&gt;,<br>    comparator: Comparator&lt;Contact&gt;,<br>    modifier: Modifier = Modifier<br>) {<br>    val sortedContacts = remember(contacts, comparator) {<br>        contacts.sortedWith(comparator)<br>    }<br>    <br>    LazyColumn(modifier) {<br>        items(sortedContacts) { contact -&gt;<br>            ContactRow(contact)<br>        }<br>    }<br>}</pre><p><strong>Why this works:</strong> The list is sorted once when ContactList is first composed. The sorted result is cached and only regenerated when contacts or comparator changes. Otherwise, the composable reuses the cached sorted list</p><p><strong>Source:</strong> <a href="https://developer.android.com/develop/ui/compose/performance/bestpractices">Android Developers — Follow best practices</a></p><h3>2. Hoist State to the Right Level</h3><h3>The Problem</h3><p>Improper state management leads to components that are difficult to test, reuse, and maintain. State hoisting is a pattern that makes composables stateless by moving state to their caller.</p><h3>❌ DON’T: Keep all state internal when it should be shared</h3><pre>@Composable<br>fun Counter() {<br>    // State is trapped inside - can&#39;t control from outside<br>    var count by remember { mutableStateOf(0) }<br>    <br>    Column {<br>        Text(text = &quot;Count: $count&quot;)<br>        Button(onClick = { count++ }) {<br>            Text(text = &quot;Increment&quot;)<br>        }<br>    }<br>}</pre><p><strong>The issue:</strong> The state is locked inside the composable, making it impossible to:</p><ul><li>Control the counter value from a parent composable</li><li>Test the composable with different states</li><li>Share the state with other composables</li><li>Preview the composable with specific values</li></ul><h3>✅ DO: Hoist state to make composables reusable</h3><pre>// Stateless composable - reusable and testable<br>@Composable<br>fun Counter(<br>    count: Int,<br>    onIncrement: () -&gt; Unit,<br>    modifier: Modifier = Modifier<br>) {<br>    Column(modifier = modifier) {<br>        Text(text = &quot;Count: $count&quot;)<br>        Button(onClick = onIncrement) {<br>            Text(text = &quot;Increment&quot;)<br>        }<br>    }<br>}</pre><pre>// State owner<br>@Composable<br>fun CounterScreen() {<br>    var count by remember { mutableStateOf(0) }<br>    Counter(<br>        count = count,<br>        onIncrement = { count++ }<br>    )<br>}</pre><p><strong>Benefits:</strong></p><ul><li><strong>Single source of truth:</strong> State is managed in one place</li><li><strong>Reusability:</strong> The Counter composable can be used in different contexts</li><li><strong>Testability:</strong> You can easily test Counter by passing different values</li><li><strong>Separation of concerns:</strong> UI logic is separated from state management</li></ul><h3>Key Guidelines for State Hoisting</h3><p>According to official Android documentation:</p><ol><li><strong>Hoist to at least the lowest common parent</strong> of all composables that use the state (read)</li><li><strong>Hoist to at least the highest level</strong> it may be changed (write)</li><li><strong>If two states change in response to the same events</strong>, they should be hoisted together</li></ol><p><strong>Sources:</strong></p><ul><li><a href="https://developer.android.com/develop/ui/compose/state">Android Developers — State and Jetpack Compose</a></li><li><a href="https://developer.android.com/develop/ui/compose/state-hoisting">Android Developers — Where to hoist state</a></li></ul><h3>3. Always Use Keys in LazyColumn/LazyRow for Dynamic Lists</h3><h3>The Problem</h3><p>Without keys, Compose tracks items by their position in the list. When items are added, removed, or reordered, this can cause incorrect state preservation and wasteful recompositions.</p><h3>❌ DON’T: Omit keys in dynamic lists</h3><pre>@Composable<br>fun NotesList(notes: List&lt;Note&gt;) {<br>    LazyColumn {<br>        items(notes) { note -&gt;  // No key provided<br>            NoteRow(note)<br>        }<br>    }<br>}</pre><p><strong>The issue:</strong> Suppose the last note is edited and becomes the most recent, moving to the top. Without keys:</p><ul><li>Compose thinks item at position 0 was deleted</li><li>Compose thinks new items were created for positions 1, 2, 3, etc.</li><li>Every single item in the list gets recomposed</li><li>Internal state (like expansion states, text fields) may be incorrectly preserved</li></ul><h3>✅ DO: Provide stable, unique keys for list items</h3><pre>@Composable<br>fun NotesList(notes: List&lt;Note&gt;) {<br>    LazyColumn {<br>        items(<br>            items = notes,<br>            key = { note -&gt; note.id }  // Stable, unique key<br>        ) { note -&gt;<br>            NoteRow(note)<br>        }<br>    }<br>}</pre><p><strong>Why this works:</strong> When a note changes position (e.g., sorted by modification time), Compose understands that it’s the same note being moved, not a new note being created. This allows Compose to:</p><ul><li>Maintain the internal state of each item correctly</li><li>Perform smart recomposition (only what changed)</li><li>Apply efficient item animations</li><li>Avoid unnecessary recreation of composables</li></ul><h3>Key Requirements</h3><ul><li><strong>Must be unique:</strong> Each item needs a distinct key</li><li><strong>Must be stable:</strong> The same item should always have the same key</li><li><strong>Based on data identity:</strong> Use IDs from your data model (e.g., user.id, product.sku)</li></ul><p><strong>Sources:</strong></p><ul><li><a href="https://developer.android.com/develop/ui/compose/performance/bestpractices">Android Developers — Follow best practices</a></li><li><a href="https://developer.android.com/jetpack/compose/lists">Android Developers — Lists and grids</a></li></ul><h3>4. Defer State Reads with derivedStateOf and Lambda Modifiers</h3><h3>The Problem</h3><p>Reading state that changes frequently can trigger excessive recompositions, even when the UI doesn’t need to update.</p><h3>❌ DON’T: Read rapidly changing state directly</h3><pre>@Composable<br>fun MyScreen() {<br>    val listState = rememberLazyListState()<br>    <br>    // BAD: Recomposes on EVERY scroll pixel<br>    val showButton = listState.firstVisibleItemIndex &gt; 0<br>    <br>    LazyColumn(state = listState) {<br>        // List items...<br>    }<br>    <br>    AnimatedVisibility(visible = showButton) {<br>        ScrollToTopButton()<br>    }<br>}</pre><p><strong>The issue:</strong> As the user scrolls, firstVisibleItemIndex changes constantly, triggering continuous recompositions even when the button visibility shouldn&#39;t change.</p><h3>✅ DO: Use derivedStateOf for derived calculations</h3><pre>@Composable<br>fun MyScreen() {<br>    val listState = rememberLazyListState()<br>    <br>    // Only recomposes when firstVisibleItemIndex crosses 0<br>    val showButton by remember {<br>        derivedStateOf {<br>            listState.firstVisibleItemIndex &gt; 0<br>        }<br>    }<br>    <br>    LazyColumn(state = listState) {<br>        // List items...<br>    }<br>    <br>    AnimatedVisibility(visible = showButton) {<br>        ScrollToTopButton()<br>    }<br>}</pre><p><strong>Why this works:</strong> derivedStateOf only triggers recomposition when the derived value actually changes. Even though firstVisibleItemIndex changes on every scroll pixel, showButton only changes when crossing the threshold (0), minimizing unnecessary recompositions.</p><h3>✅ DO: Defer state reads to layout phase with lambda modifiers</h3><pre>@Composable<br>private fun Title(snack: Snack, scrollProvider: () -&gt; Int) {<br>    Column(<br>        modifier = Modifier<br>            .offset { <br>                // State read happens in layout phase, not composition<br>                IntOffset(x = 0, y = scrollProvider()) <br>            }<br>    ) {<br>        // Content...<br>    }<br>}</pre><p><strong>Why this works:</strong> By using the lambda version of offset, the state read is deferred to the layout phase. When the scroll value changes:</p><ul><li>Composition phase is skipped</li><li>Only the layout phase runs</li><li>Much more efficient for frequently changing values</li></ul><p><strong>Sources:</strong></p><ul><li><a href="https://developer.android.com/develop/ui/compose/performance/bestpractices">Android Developers — Follow best practices</a></li><li><a href="https://proandroiddev.com/jetpack-compose-best-practices-you-must-always-remember-98382b132d44">ProAndroidDev — Jetpack Compose best practices</a></li></ul><h3>5. Follow Proper Modifier Parameter Patterns</h3><h3>The Problem</h3><p>Incorrect modifier usage can limit composable reusability and violate Compose’s design principles.</p><h3>❌ DON’T: Apply restrictive modifiers internally or use multiple Modifier parameters</h3><pre>@Composable<br>fun CustomButton(<br>    text: String,<br>    onClick: () -&gt; Unit<br>    // NO modifier parameter - bad!<br>) {<br>    Button(<br>        onClick = onClick,<br>        modifier = Modifier<br>            .fillMaxWidth()  // Forces full width - limits reusability<br>            .padding(16.dp)  // Forces specific padding<br>    ) {<br>        Text(text)<br>    }<br>}</pre><p><strong>The issue:</strong> The composable is locked into specific layout constraints. Callers cannot:</p><ul><li>Use it in different widths</li><li>Control its padding</li><li>Apply their own modifiers</li><li>Reuse it flexibly</li></ul><h3>❌ DON’T: Use multiple Modifier parameters</h3><pre>@Composable<br>fun CustomCard(<br>    content: @Composable () -&gt; Unit,<br>    containerModifier: Modifier = Modifier,  // Bad - multiple modifiers<br>    contentModifier: Modifier = Modifier     // Bad - multiple modifiers<br>) {<br>    Card(modifier = containerModifier) {<br>        Box(modifier = contentModifier) {<br>            content()<br>        }<br>    }<br>}</pre><p><strong>The issue:</strong> This violates Compose guidelines. Each composable should have exactly one Modifier parameter.</p><h3>✅ DO: Accept and forward Modifier parameter</h3><pre>@Composable<br>fun CustomButton(<br>    text: String,<br>    onClick: () -&gt; Unit,<br>    modifier: Modifier = Modifier  // First optional parameter<br>) {<br>    Button(<br>        onClick = onClick,<br>        modifier = modifier  // Forward to root composable<br>            .padding(16.dp)<br>            .fillMaxWidth()<br>    ) {<br>        Text(text)<br>    }<br>}</pre><pre>// Usage - caller can customize<br>CustomButton(<br>    text = &quot;Click Me&quot;,<br>    onClick = { },<br>    modifier = Modifier<br>        .padding(top = 8.dp)  // Caller controls outer layout<br>        .width(200.dp)<br>)</pre><p><strong>Why this works:</strong></p><ul><li>Caller has full control over the composable’s appearance and layout</li><li>Composable is reusable in different contexts</li><li>Follows Compose API guidelines</li></ul><h3>Modifier Best Practices</h3><ol><li><strong>Always accept a Modifier parameter</strong> named modifier</li><li><strong>Make it the first optional parameter</strong></li><li><strong>Pass it to the root composable</strong> you emit</li><li><strong>Never apply these modifiers internally:</strong></li></ol><ul><li>fillMaxWidth(), fillMaxHeight(), fillMaxSize()</li><li>width(), height()</li><li>padding() (at the root level)</li><li>Any layout-controlling modifiers</li></ul><p><strong>Sources:</strong></p><ul><li><a href="https://developer.android.com/develop/ui/compose/api-guidelines">Android Developers — API Guidelines for Jetpack Compose</a></li><li><a href="https://medium.com/simform-engineering/the-ultimate-guide-to-writing-clean-jetpack-compose-254db92cb4df">Medium — The Ultimate Guide to Writing Clean Jetpack Compose</a></li></ul><h3>Conclusion</h3><p>Following these five best practices will significantly improve your Jetpack Compose applications:</p><ol><li><strong>Cache expensive calculations</strong> with remember to avoid redundant work</li><li><strong>Hoist state properly</strong> to the lowest common ancestor for better reusability and testability</li><li><strong>Use keys in lazy lists</strong> to enable smart recomposition and maintain state correctly</li><li><strong>Defer state reads</strong> with derivedStateOf and lambda modifiers to minimize recompositions</li><li><strong>Follow Modifier patterns</strong> to create flexible, reusable composables</li></ol><p>By adhering to these guidelines backed by official Android documentation, you’ll create more performant, maintainable, and professional Compose UIs.</p><h3>Additional Resources</h3><ul><li><a href="https://developer.android.com/develop/ui/compose/performance/bestpractices">Android Developers — Performance best practices</a></li><li><a href="https://developer.android.com/develop/ui/compose/state">Android Developers — State and Jetpack Compose</a></li><li><a href="https://developer.android.com/jetpack/compose/lists">Android Developers — Lists and grids</a></li><li><a href="https://developer.android.com/develop/ui/compose/api-guidelines">Android Developers — API Guidelines</a></li><li><a href="https://getstream.io/blog/jetpack-compose-guidelines/">Stream — Jetpack Compose Guidelines</a></li></ul><p><em>Happy Composing! 🚀</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5f802d6b2ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>