<?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 Ahmed Omara on Medium]]></title>
        <description><![CDATA[Stories by Ahmed Omara on Medium]]></description>
        <link>https://medium.com/@ahmedomara1?source=rss-d9a3850dcba0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bw9Ql5BlGo0eZBmvMXk8Og.png</url>
            <title>Stories by Ahmed Omara on Medium</title>
            <link>https://medium.com/@ahmedomara1?source=rss-d9a3850dcba0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 03:15:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahmedomara1/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[Threads, Concurrency, and What Actually Runs Your Mobile App]]></title>
            <link>https://ahmedomara1.medium.com/threads-concurrency-and-what-actually-runs-your-mobile-app-8835c22e009e?source=rss-d9a3850dcba0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8835c22e009e</guid>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mobile-engineering]]></category>
            <dc:creator><![CDATA[Ahmed Omara]]></dc:creator>
            <pubDate>Sat, 10 Oct 2026 21:23:00 GMT</pubDate>
            <atom:updated>2026-10-10T21:23:00.962Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*54Lp1wpdC4f9--kBTsnAxA.jpeg" /></figure><p>You know what’s interesting about mobile development? We spend so much time working with frameworks, libraries, state management, and UI that sometimes we forget what’s actually happening underneath.</p><p>We write async and await, move work to the background, and expect everything to run smoothly. But then the UI freezes, an old API response overwrites the latest data, or a bug appears only under certain conditions.</p><p>And you’re left wondering: what actually happened here?</p><p>Understanding threads, concurrency, shared memory, and asynchronous execution can explain many of the problems we face in everyday mobile development.</p><p>What I find interesting is that these concepts aren’t limited to Android, iOS, or Flutter. The APIs differ, and each platform has its own runtime and execution model, but many of the underlying ideas are surprisingly similar.</p><p>Let’s start with the basics.</p><h3>Your app is a process, but it doesn’t run on just one thread</h3><p>When you open a mobile app, the operating system gives it an execution environment called a process.</p><p>A process has its own virtual address space and resources. Your app’s objects, runtime data, loaded libraries, and other resources exist within that environment.</p><p>If you open a banking app and then switch to a social media app, they’re generally running in separate processes. One app can’t simply access the other’s memory whenever it wants. The operating system provides isolation between these environments.</p><p>But here’s where things get interesting: <strong>a single process can contain multiple threads.</strong></p><p>A thread is an execution path within a process. Each thread has its own execution state and stack, while threads belonging to the same process share memory and many other resources.</p><p>Think of it this way:</p><ul><li>The <strong>process</strong> provides the environment and resources in which the app runs.</li><li>The <strong>threads</strong> execute instructions within that environment.</li><li>The <strong>shared memory</strong> allows those threads to access common objects and state.</li></ul><p>This shared memory is useful because threads can work with the same data without communicating through a separate process.</p><p>But it also introduces an important question: what happens when two threads try to modify the same data at nearly the same time?</p><p>Before answering that, we need to understand another distinction.</p><h3>Concurrency doesn’t always mean parallelism</h3><p>People often use <em>concurrency</em> and <em>parallelism</em> as if they’re interchangeable. They’re related, but they describe different things.</p><p><strong>Concurrency</strong> is about managing multiple tasks that can make progress during overlapping periods of time.</p><p><strong>Parallelism</strong> is when multiple tasks actually execute at the same time, typically on different CPU cores.</p><p>Imagine your app needs to fetch portfolio data from an API while the user continues interacting with the screen.</p><p>The API request might spend most of its time waiting for a response. While that happens, the app can handle other work instead of blocking everything until the request finishes.</p><p>The tasks overlap in time, but they’re not necessarily executing on the CPU simultaneously.</p><p>Now imagine two independent calculations running on separate CPU cores. Both calculations can execute at the same instant. That’s parallelism.</p><p>Why does this distinction matter?</p><p>Because the type of work determines how we should approach it.</p><p>For network requests, we generally want asynchronous, non-blocking operations so the app can continue making progress while waiting.</p><p>For CPU-intensive work, such as processing a large dataset or performing expensive calculations, we need to consider where that work executes and whether parallel execution would help.</p><p>Moving everything to a background thread isn’t automatically the right answer. Small tasks might not benefit from it, and scheduling or data-transfer overhead can sometimes cost more than the work itself.</p><p>The important thing is to understand what the code is doing before deciding how it should run.</p><h3>So, does async mean another thread?</h3><p>This is one of the most common misconceptions when working across different mobile platforms.</p><p>You see code like this:</p><p><strong>Kotlin</strong></p><pre>val portfolio = repository.getPortfolio()</pre><p><strong>Swift</strong></p><pre>let portfolio = try await service.getPortfolio()</pre><p><strong>Dart</strong></p><pre>final portfolio = await api.getPortfolio();</pre><p>The syntax differs, but the underlying question is similar: what happens while we’re waiting for the result?</p><p>Here’s the key point: <strong>asynchronous execution doesn’t automatically mean a new thread is created.</strong></p><p>Suppose an API request takes 800 milliseconds to finish. With a properly implemented asynchronous operation, execution can suspend while waiting for the response, allowing other work to proceed.</p><p>When the response arrives, execution continues.</p><p>No dedicated thread is necessarily required just to wait for a network response.</p><p>However, if a function performs blocking work, calling it from an asynchronous function doesn’t magically make that work non-blocking.</p><p>To understand why, let’s look at how each platform handles asynchronous execution.</p><h3>Kotlin Coroutines</h3><p>Kotlin Coroutines let us write asynchronous code without building everything around callbacks.</p><p>For example:</p><pre>suspend fun loadPortfolio(): Portfolio {<br>    return api.getPortfolio()<br>}</pre><p>The suspend keyword doesn&#39;t mean &quot;run this on a background thread.&quot;</p><p>It means the function can suspend and resume through Kotlin’s coroutine machinery. Whether the underlying operation blocks a thread depends on how that operation is implemented.</p><p>If we need to perform CPU-intensive work, we can use an appropriate dispatcher:</p><pre>suspend fun calculatePortfolio(<br>    data: PortfolioData<br>): Portfolio {<br>    return withContext(Dispatchers.Default) {<br>        performCalculation(data)<br>    }<br>}</pre><p>Dispatchers.Default is designed for CPU-intensive work.</p><p>For blocking I/O operations, such as reading a file using a blocking API, Dispatchers.IO is commonly used:</p><pre>suspend fun readLocalFile(): String {<br>    return withContext(Dispatchers.IO) {<br>        file.readText()<br>    }<br>}</pre><p>The dispatcher determines where the coroutine’s work is scheduled.</p><p>A coroutine isn’t the same thing as a thread. Multiple coroutines can use the same thread, and a coroutine can resume on a different thread depending on its execution context.</p><p>This is one of the reasons coroutines are useful: they let us manage many concurrent operations without needing a dedicated thread for every operation.</p><p>But choosing the right dispatcher still matters. A coroutine running blocking code on the main thread can freeze the UI, regardless of whether the function is marked suspend.</p><h3>Swift Concurrency</h3><p>Swift provides async and await to express asynchronous operations:</p><pre>func loadPortfolio() async throws -&gt; Portfolio {<br>    try await service.getPortfolio()<br>}</pre><p>Just like Kotlin, declaring a function async doesn&#39;t automatically mean it starts on a separate background thread.</p><p>Swift Concurrency manages asynchronous tasks through its concurrency runtime, but we still need to think about CPU-intensive work and access to UI-related state.</p><p>For example:</p><pre>@MainActor<br>func updatePortfolio(_ portfolio: Portfolio) {<br>    self.portfolio = portfolio<br>}</pre><p>MainActor provides an isolation mechanism for state that should be accessed through the main actor, which is commonly used for UI-related state.</p><p>Actors can also help protect mutable state by controlling access to it.</p><p>This doesn’t mean every function needs an actor or that we should manually move everything to the background. The goal is to make execution and state ownership explicit where it matters.</p><h3>Dart and Flutter</h3><p>Dart also supports asynchronous programming through Future, async, and await:</p><pre>Future&lt;Portfolio&gt; loadPortfolio() async {<br>  return await api.getPortfolio();<br>}</pre><p>In Flutter, the main isolate executes Dart code responsible for much of the application’s UI logic.</p><p>When we await a normal asynchronous network request, the main isolate doesn’t have to sit blocked until the response arrives.</p><p>But there’s an important catch.</p><p>If we run a massive synchronous calculation on the same isolate, the UI can still freeze.</p><p>For CPU-intensive work, Dart isolates can help:</p><pre>final result = await Isolate.run(() {<br>  return calculateLargeDataset(data);<br>});</pre><p>An isolate has its own memory and execution state. Unlike ordinary threads that share mutable memory, isolates generally communicate through messages or transferable data.</p><p>This reduces certain shared-memory problems, although it introduces its own communication and data-transfer costs.</p><p>And just to be clear, async doesn&#39;t create an isolate either.</p><p>Across Kotlin, Swift, and Dart, the lesson is similar: asynchronous execution, thread scheduling, and parallel execution are related concepts, but they’re not the same thing.</p><h3>The UI doesn’t have unlimited time</h3><p>Let’s say you’re working on an investment app.</p><p>A user opens a portfolio screen, and you need to calculate the total value of thousands of positions. You write the calculation and execute it directly on the path responsible for keeping the UI responsive.</p><p>The calculation takes 150 milliseconds.</p><p>Now scrolling feels terrible. Buttons don’t respond immediately, and animations start to stutter.</p><p>What happened?</p><p>The UI was busy doing something else.</p><p>Mobile interfaces need to produce frames as the user interacts with them. At 60 Hz, a display refresh interval is approximately 16.67 milliseconds. At 120 Hz, it’s approximately 8.33 milliseconds.</p><p>These aren’t strict limits for every individual function because rendering involves multiple stages. But they illustrate why even relatively short blocking operations can become noticeable.</p><p>Imagine the UI is ready to process another frame, but your code starts a synchronous calculation that takes 100 milliseconds.</p><p>Instead of progressing smoothly, rendering has to wait until that work finishes.</p><p>The result is dropped frames, delayed interactions, and a generally unresponsive experience.</p><p>This is why we need to distinguish between asynchronous I/O and CPU-intensive work.</p><p>An asynchronous network request can spend time waiting without continuously occupying the UI thread or isolate.</p><p>A large synchronous calculation, on the other hand, can keep the UI execution path busy for its entire duration.</p><p>In Flutter, a simplified example might look like this:</p><pre>Future&lt;void&gt; loadPortfolio() async {<br>  final response = await api.getPortfolio();</pre><pre>  final result = await Isolate.run(() {<br>    return calculateLargePortfolio(response);<br>  });</pre><pre>  if (!mounted) return;</pre><pre>  setState(() {<br>    portfolio = result;<br>  });<br>}</pre><p>The request fetches the data, the expensive calculation runs in another isolate, and the UI updates when the result is ready.</p><p>In a production implementation, we’d also handle errors, account for stale responses, and consider whether the calculation is large enough to justify an isolate.</p><p>The same principle applies to Android and iOS, although the tools differ.</p><p><strong>The goal isn’t to move everything away from the UI. It’s to prevent expensive or blocking work from interfering with it.</strong></p><h3>Shared memory is useful until two threads start changing the same thing</h3><p>Remember that threads inside the same process can access shared memory?</p><p>Let’s see why that matters.</p><p>Imagine we have a simple counter:</p><pre>var count = 0</pre><pre>fun increment() {<br>    count++<br>}</pre><p>Nothing complicated here.</p><p>But count++ isn&#39;t necessarily one indivisible operation. Conceptually, it reads the current value, adds one, and writes the result back.</p><p>Now imagine two threads execute the function at nearly the same time.</p><p>Both threads read 0.</p><p>Both calculate 1.</p><p>Both write 1.</p><p>The final result is 1, even though we expected 2.</p><p>This is a <strong>race condition</strong>. The result depends on the timing and ordering of operations that access shared state.</p><p>The frustrating part is that these bugs can be difficult to reproduce. Your code might work perfectly during testing and then fail under heavier load or when the operating system schedules threads differently.</p><p>There are several ways to address this.</p><p>For a simple counter on the JVM, we can use an atomic integer:</p><pre>private val count = AtomicInteger(0)</pre><pre>fun increment() {<br>    count.incrementAndGet()<br>}</pre><p>The increment operation is atomic, so concurrent updates won’t overwrite each other in the way shown earlier.</p><p>Another option is synchronization:</p><pre>private val lock = Any()<br>private var count = 0</pre><pre>fun increment() {<br>    synchronized(lock) {<br>        count++<br>    }<br>}</pre><p>The synchronized block ensures that threads using the same lock can’t execute that protected section simultaneously.</p><p>However, these approaches aren’t interchangeable in every situation.</p><p>An atomic counter is appropriate for a simple independent update. A lock can protect a more complex operation involving several pieces of shared state that must remain consistent.</p><p>Sometimes, the better solution is to avoid sharing mutable state altogether.</p><p>Instead of letting several threads modify the same object, we can give each task its own data and combine the results later. Actors, ownership-based approaches, and message passing can also help control how state changes.</p><p>Less shared mutable state generally means fewer opportunities for concurrency bugs.</p><h3>volatile won&#39;t magically fix your race conditions</h3><p>While we’re talking about shared state, there’s another concept worth understanding: memory visibility.</p><p>Imagine one thread updates a flag, while another thread reads it. How do we ensure the second thread observes the update?</p><p>On the JVM, @Volatile provides visibility and memory-ordering guarantees for a variable according to the Java Memory Model.</p><p>For example:</p><pre>@Volatile<br>var isReady = false</pre><p>This is useful when one thread updates a flag and another thread needs to observe the change.</p><p>But consider this:</p><pre>@Volatile<br>var count = 0</pre><pre>fun increment() {<br>    count++<br>}</pre><p>This still has a race condition if multiple threads increment count concurrently.</p><p>Why?</p><p>Because count++ still involves reading, modifying, and writing the value. @Volatile doesn&#39;t turn those separate steps into one atomic operation.</p><p>It helps to distinguish three concepts:</p><ul><li><strong>Atomicity:</strong> Does an operation happen as one indivisible unit?</li><li><strong>Visibility:</strong> Can another thread observe a change?</li><li><strong>Ordering:</strong> What guarantees exist about the order in which operations become observable?</li></ul><p>They’re related, but solving one problem doesn’t automatically solve the others.</p><p>This is why concurrency bugs aren’t always fixed by adding a keyword or wrapping a function in a new API. We need to understand which guarantee the code actually requires.</p><h3>Sometimes the problem isn’t shared memory. It’s timing.</h3><p>Here’s another situation that appears frequently in real apps.</p><p>Imagine a user opens a portfolio screen and selects January. The app starts loading January’s data.</p><p>Before the request finishes, the user selects February. The app starts another request.</p><p>Now suppose February’s response arrives first, so the screen displays the correct data.</p><p>A moment later, January’s response arrives and overwrites it.</p><p>Suddenly, the user is looking at January’s portfolio while February is selected.</p><p>Notice that this can happen even when we’re using asynchronous APIs correctly.</p><p>We don’t necessarily have two threads modifying the same memory simultaneously. The issue is that requests can finish in a different order from the order in which they started.</p><p>One simple solution is to give each request an identifier:</p><pre>int _requestId = 0;</pre><pre>Future&lt;void&gt; loadPortfolio(String month) async {<br>  final requestId = ++_requestId;</pre><pre>  try {<br>    final result = await api.getPortfolio(month);</pre><pre>    if (requestId != _requestId) return;<br>    if (!mounted) return;</pre><pre>    setState(() {<br>      portfolio = result;<br>    });<br>  } catch (error) {<br>    if (requestId != _requestId) return;</pre><pre>    // Handle the current request&#39;s error.<br>  }<br>}</pre><p>Every time a new request starts, the identifier changes. When a response arrives, we check whether it still belongs to the latest request.</p><p>If it doesn’t, we ignore it.</p><p>This is just one approach. Depending on the architecture, we might use cancellation, request deduplication, or state-management logic that prevents stale results from being applied.</p><p>For example, in a search screen, we generally want the results for the latest query, not whichever request happens to finish last.</p><p>The important distinction is that concurrency problems aren’t limited to threads racing over shared memory. They can also arise from asynchronous operations completing in an unexpected order.</p><h3>And then there’s the problem of deadlocks</h3><p>Race conditions aren’t the only way concurrency can go wrong.</p><p>A deadlock occurs when tasks end up waiting for each other in a way that prevents them from continuing.</p><p>Imagine Thread A acquires Lock 1 and then tries to acquire Lock 2.</p><p>At the same time, Thread B acquires Lock 2 and tries to acquire Lock 1.</p><p>Thread A can’t continue until Thread B releases Lock 2. But Thread B can’t continue until Thread A releases Lock 1.</p><p>Neither can make progress.</p><p>One way to reduce this risk is to acquire locks in a consistent order. It’s also a good idea to keep critical sections small and avoid holding locks while performing slow operations.</p><p>Deadlocks aren’t something you’ll encounter every day, but when you’re working with multiple locks and shared state, understanding how they happen is valuable.</p><h3>What I find useful about all this</h3><p>The same fundamental concepts keep appearing, even when we switch frameworks.</p><p>With Kotlin Coroutines, we need to understand dispatchers, suspension, and shared state.</p><p>With Swift Concurrency, we need to understand tasks, actors, and where UI-related work belongs.</p><p>With Dart and Flutter, we need to understand asynchronous operations, the UI isolate, and when CPU-intensive work needs a separate isolate.</p><p>The APIs aren’t identical, and the runtimes don’t behave exactly the same way. But the questions we need to ask are surprisingly similar.</p><p>Where is this work running?</p><p>Is it waiting for something, or consuming CPU?</p><p>Can it block the UI?</p><p>Can multiple operations overlap?</p><p>What happens if they finish in the wrong order?</p><p>And if multiple tasks access the same state, what prevents them from interfering with one another?</p><p>I think these are much more useful questions than simply asking whether a function should be async or run on a background thread.</p><p>Sometimes the problem isn’t that we’re running something on the wrong thread. Sometimes we’re blocking the UI, sharing mutable state without proper synchronization, or applying a response that is no longer relevant.</p><p>Those are very different problems, even if they all show up as bugs in the same app.</p><p>We don’t need to think about every detail of the runtime whenever we write a function. But when something behaves strangely, understanding what’s happening underneath gives us a much better chance of finding the actual cause instead of trying random fixes.</p><p>That’s what makes these concepts useful: not memorizing definitions, but understanding why our apps behave the way they do.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8835c22e009e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Benchmarking in Android]]></title>
            <link>https://ahmedomara1.medium.com/benchmarking-in-android-48afc5054510?source=rss-d9a3850dcba0------2</link>
            <guid isPermaLink="false">https://medium.com/p/48afc5054510</guid>
            <category><![CDATA[benchmark]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Ahmed Omara]]></dc:creator>
            <pubDate>Mon, 06 Oct 2025 22:47:43 GMT</pubDate>
            <atom:updated>2025-10-06T22:47:43.094Z</atom:updated>
            <content:encoded><![CDATA[<p>Performance is one of the most critical aspects of user experience.<br>Fast apps feel professional, while slow or janky apps quickly lose users.</p><p>But how can we measure performance accurately?<br>That’s where <strong>Benchmarking</strong> comes in.</p><h3>What is Benchmarking?</h3><p>A <strong>benchmark</strong> is a test that measures how efficiently a piece of code runs — for example:</p><ul><li>Function execution time</li><li>Algorithm performance</li><li>Database query speed</li></ul><p>Benchmarks run as <strong>instrumented tests</strong> on a real or virtual device (but <strong>not in debug mode</strong>).</p><h3>Types of Benchmarks</h3><p>Android provides two main benchmark types:</p><ul><li>Microbenchmark: Measures <strong>small, isolated code</strong> — such as methods, APIs, or library calls.</li><li>Macrobenchmark: Measures <strong>large app behaviors</strong>, like startup, rendering, or scrolling.</li></ul><blockquote><em>💡 Always run benchmarks on a </em><strong><em>real device</em></strong><em> and a </em><strong><em>release (non-debuggable) build</em></strong><em> for accurate results.</em></blockquote><h3>Why Use Macrobenchmark?</h3><p><strong>Macrobenchmarks</strong> are used to measure end-to-end app performance, such as:</p><ol><li><strong>Startup Time</strong> — how long your app takes to open</li><li><strong>Scrolling Performance</strong> — frame rates and smoothness</li><li><strong>UI Interaction</strong> — transitions or navigation</li><li><strong>Jank &amp; Frame Drops</strong> — responsiveness during animations or gestures</li></ol><h3>Setting Up Macrobenchmark</h3><p>We create a separate module (usually named Macrobenchmark) and add the <strong>Android Macrobenchmark library</strong> to it.</p><p>This module runs instrumented tests that launch your app and measure performance metrics using MacrobenchmarkRule.</p><p>Example:</p><pre>@get:Rule<br>val benchmarkRule = MacrobenchmarkRule()<br><br>@Test<br>fun scrollPerformanceTest() = benchmarkRule.measureRepeated(<br>    packageName = &quot;com.omaradev.benchmark&quot;,<br>    metrics = listOf(FrameTimingMetric()),<br>    iterations = 5<br>) {}</pre><h3>Explanation</h3><ul><li><strong>MacrobenchmarkRule</strong> → sets up the environment for performance tests</li><li><strong>measureRepeated</strong> → runs your test multiple times to get stable results</li><li><strong>metrics</strong> → defines what you’re measuring (startup, frame timing, etc.)</li><li><strong>iterations</strong> → number of test repetitions for accuracy</li></ul><h3>Types of Metrics in Benchmarking</h3><p>When running benchmarks, you can collect different metrics depending on the aspect of performance being tested.</p><h3>1. Startup Timing Metrics</h3><p><strong>Purpose:</strong> Measure how long it takes for your app to start and show its first frame.</p><p><strong>Startup Modes:</strong></p><ul><li><strong>Cold Start:</strong> App not running at all (first launch after boot)</li><li><strong>Warm Start:</strong> App in memory, but activity recreated</li><li><strong>Hot Start:</strong> App already in memory, just brought to foreground</li></ul><p>Example:</p><pre>@RunWith(AndroidJUnit4::class)<br>class StartupBenchmark {<br><br>    @get:Rule<br>    val benchmarkRule = MacrobenchmarkRule()<br><br><br>    @Test<br>    fun startupCold() = benchmarkRule.measureRepeated(<br>        packageName = &quot;com.omaradev.benchmark&quot;,<br>        metrics = listOf(StartupTimingMetric()),<br>        iterations = 5,<br>        startupMode = StartupMode.COLD<br>    ) {<br>        pressHome()<br>        startActivityAndWait()<br>    }<br><br><br>    @Test<br>    fun startupWarm() = benchmarkRule.measureRepeated(<br>        packageName = &quot;com.omaradev.benchmark&quot;,<br>        metrics = listOf(StartupTimingMetric()),<br>        iterations = 5,<br>        startupMode = StartupMode.WARM<br>    ) {<br>        pressHome()<br>        startActivityAndWait()<br>    }<br><br>    @Test<br>    fun startupHot() = benchmarkRule.measureRepeated(<br>        packageName = &quot;com.omaradev.benchmark&quot;,<br>        metrics = listOf(StartupTimingMetric()),<br>        iterations = 5,<br>        startupMode = StartupMode.HOT<br>    ) {<br>        pressHome()<br>        startActivityAndWait()<br>    }<br>}</pre><p><strong>Output:</strong></p><p>The benchmark results show the <strong>minimum</strong>, <strong>median</strong>, and <strong>maximum</strong> startup times</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JSY1iobW2cjiOJaG4DjU9Q.png" /></figure><p><strong>2. Frame Timing Metrics</strong></p><p><strong>Purpose:</strong> Measure <strong>UI smoothness</strong> by analyzing how fast frames are rendered and detecting any <strong>jank</strong> or dropped frames.</p><p>This helps you find performance bottlenecks during animations, scrolling, or UI transitions.</p><pre>@RunWith(AndroidJUnit4::class)<br>class FrameBenchmark {<br><br>    @get:Rule<br>    val benchmarkRule = MacrobenchmarkRule()<br><br>    @Test<br>    fun scrollBadExample() = benchmarkRule.measureRepeated(<br>        packageName = &quot;com.omaradev.benchmark&quot;,<br>        metrics = listOf(FrameTimingMetric()),<br>        iterations = 5<br>    ) {<br>        // Launch app<br>        pressHome()<br>        startActivityAndWait()<br><br>        // Wait until product list is visible<br>        device.wait(Until.hasObject(By.text(&quot;Product #0&quot;)), 5_000)<br><br>        // Scroll to a product using UiAutomator<br>        val list = device.findObject(By.scrollable(true))<br>        list.scroll(Direction.DOWN, 5.0f)<br><br>    }<br><br>    @Test<br>    fun scrollGoodExample() = benchmarkRule.measureRepeated(<br>        packageName = &quot;com.omaradev.benchmark&quot;,<br>        metrics = listOf(FrameTimingMetric()),<br>        iterations = 5<br>    ) {<br>        pressHome()<br>        startActivityAndWait()<br><br>        val goodButton = device.findObject(<br>            By.text(&quot;Good Example&quot;)<br>        )<br>        goodButton.click()<br><br>        device.wait(Until.hasObject(By.text(&quot;Product #0&quot;)),5_000)<br><br>        val list = device.findObject(By.scrollable(true))<br>        list.scroll(Direction.DOWN,5.0f)<br>    }<br><br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*52PJNk-3J51yljmUsFIXng.png" /></figure><p><strong>Output:</strong></p><p>This test produces metrics such as:</p><ul><li><strong>frameOverrunMs</strong> → How late a frame was relative to the expected frame time (e.g., 60 fps → 16 ms per frame)</li><li><strong>frameDurationCpuMs</strong> → How long each frame took to render on the CPU</li></ul><p>You’ll also see percentiles like:</p><ul><li><strong>P50</strong> → 50% of frames took less than this time</li><li><strong>P90</strong> → 90% of frames were faster than this</li><li><strong>P95</strong> → 95% of frames were faster than this</li></ul><blockquote><em>💡 </em>Each device renders frames based on its refresh rate (e.g., 60 Hz → 16.67 ms, 90 Hz → 11.11 ms, 120 Hz → 8.33 ms).</blockquote><blockquote>If rendering takes longer than this time, the frame is delayed — causing <strong>jank</strong>.<em>(Formula: 1000 / fps = frame time in ms)</em></blockquote><p><strong>3. Power Metrics</strong></p><p><strong>Purpose:</strong> Measure power usage (CPU, GPU, Display) while performing specific actions — for example, scrolling through a LazyColumn.</p><p>This helps identify <strong>energy-hungry parts</strong> of your UI or logic that drain the battery.</p><p>Example</p><pre>@RunWith(AndroidJUnit4::class)<br>class PowerBenchmark {<br><br>    @get:Rule<br>    val benchmarkRule = MacrobenchmarkRule()<br><br>    @OptIn(ExperimentalMetricApi::class)<br>    @RequiresApi(Build.VERSION_CODES.Q)<br>    val powerMetric = PowerMetric(<br>        PowerMetric.Power(<br>            categories = mapOf(<br>                PowerCategory.CPU to PowerCategoryDisplayLevel.TOTAL,<br>                PowerCategory.DISPLAY to PowerCategoryDisplayLevel.BREAKDOWN<br>            )<br>        )<br>    )<br><br><br>    @OptIn(ExperimentalMetricApi::class)<br>    @RequiresApi(Build.VERSION_CODES.Q)<br>    @Test<br>    fun scrollEnergyCost() = benchmarkRule.measureRepeated(<br>        packageName = &quot;com.omaradev.benchmark&quot;,<br>        metrics = listOf(powerMetric),<br>        iterations = 3<br>    ) {<br>        pressHome()<br>        startActivityAndWait()<br><br>        device.wait(Until.hasObject(By.text(&quot;Product #0&quot;)),5_000)<br><br><br>        val list = UiScrollable(UiSelector().scrollable(true))<br>        list.scrollTextIntoView(&quot;Product #50&quot;)<br>    }<br>}</pre><p><strong>Output:</strong></p><p>Reports how much CPU and display energy was consumed during scrolling. helping you optimize for <strong>battery efficiency</strong>.</p><h3>Microbenchmark in Android</h3><p>While <strong>Macrobenchmark</strong> tests app-level performance (startup, rendering, scrolling),<br> <strong>Microbenchmark</strong> focuses on <strong>small, isolated pieces of code </strong>such as functions, algorithms, or repository logic to ensure your app’s core logic remains efficient.</p><p><strong>This project demonstrates how to apply Microbenchmarking in a clean architecture setup.</strong></p><h3>Project Structure</h3><pre>domain/<br> ├── usecase/        → Business logic (e.g., GetPostsUseCase)<br> ├── model/          → Object creation, sorting<br>data/<br> ├── repository/     → Repository implementation<br> ├── remote/         → JSON serialization/deserialization</pre><h4>Example: Benchmarking Domain Layer (GetPostsUseCase)</h4><pre>class GetPostsUseCaseBenchmark {<br><br>    @get:Rule<br>    val benchmarkRule = BenchmarkRule()<br><br>    private val repository = FakePostRepository()<br>    private val useCase = GetPostsUseCase(repository)<br><br>    @Test<br>    fun getPostsPerformance() = benchmarkRule.measureRepeated {<br>        val posts = useCase.invoke()<br>        check(posts.isNotEmpty()) // avoid optimization<br>    }<br>}</pre><p><strong>What this measures:</strong></p><ul><li>Execution time of GetPostsUseCase</li><li>Repository response time (mocked with FakePostRepository)</li><li>Ensures retrieving posts remains efficient</li></ul><h4>Example: Benchmarking Model Sorting</h4><pre>class PostSortingBenchmark {<br><br>    @get:Rule<br>    val benchmarkRule = BenchmarkRule()<br><br>    @Test<br>    fun sortPostsBenchmark() {<br>        val posts = List(10_000) { Post(it, &quot;Title $it&quot;, &quot;Content $it&quot;) }.shuffled()<br>        <br>        benchmarkRule.measureRepeated {<br>            val sortedPosts = posts.sortedBy { it.title }<br>            check(sortedPosts.firstOrNull()?.id != -1)<br>        }<br>    }<br>}</pre><p><strong>What this measures:</strong></p><ul><li>Sorting performance for large lists of posts</li><li>Efficiency of sortedBy() in Kotlin across iterations</li></ul><h3>🔗 Project Source Code</h3><p>You can find the full source code for both <strong>Microbenchmark</strong> and <strong>Macrobenchmark</strong> modules on GitHub:<br> 👉<a href="https://github.com/AhmedOmara14/Benchmark?tab=readme-ov-file"> GitHub Repository — Android Benchmark Project</a></p><h3>Conclusion</h3><p>Benchmarking isn’t just about numbers — it’s about understanding how your app behaves under real conditions.<br> By using <strong>Microbenchmarks</strong>, you can ensure your functions and logic remain efficient.<br> And with <strong>Macrobenchmarks</strong>, you can validate that your app’s UI and startup performance deliver a smooth experience to users.</p><p>Together, they help you write <strong>faster, more reliable, and professional Android apps</strong>.<br> Start small, measure often, and optimize only what matters.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48afc5054510" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Memory Consumption]]></title>
            <link>https://ahmedomara1.medium.com/optimizing-memory-consumption-694399e6586d?source=rss-d9a3850dcba0------2</link>
            <guid isPermaLink="false">https://medium.com/p/694399e6586d</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-studio]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Ahmed Omara]]></dc:creator>
            <pubDate>Sun, 28 Sep 2025 20:21:37 GMT</pubDate>
            <atom:updated>2025-09-28T20:21:37.492Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qIG39I1MFYryho17KNmwaw.png" /></figure><p>Jetpack Compose accelerates UI development through its declarative nature, fundamentally changing how we approach performance and memory management.</p><p>Developers transitioning from the traditional View system may be surprised by how easily <strong>unnecessary object allocations</strong> can proliferate during <strong>recomposition</strong>, leading to significantly higher memory usage and more frequent <strong>Garbage Collection (GC)</strong> cycles.</p><p>This article explores how to effectively <strong>track memory consumption</strong> using the <strong>Android Studio Profiler</strong> and details common pitfalls and best practices for creating memory-efficient Compose UIs.</p><p><strong>Why Track Memory Consumption?</strong></p><p>Memory issues rarely crash your app immediately. Tracking usage early helps you:</p><ul><li><strong>Measure Allocations / Deallocations</strong>: Monitor how many objects are created and released over time.</li><li><strong>Identify Leaks</strong>: Detect objects that live longer than expected.</li><li><strong>Spot Memory Spikes</strong>: Find which Composable or operation triggers sudden jumps in memory usage.</li></ul><p><strong>Real Example: Bad vs Good</strong></p><p>Consider rendering a large list of products inside a LazyColumn.</p><p>❌<strong> Bad Example — Inefficient Memory Usage</strong></p><pre>@Composable<br>fun BadProductList(productsJson: List&lt;String&gt;) {<br>    val context = LocalContext.current<br>    LazyColumn {<br>        items(productsJson.size) { index -&gt;<br>            // ❌ Parsing JSON for every item on every recomposition<br>            val product = Json.decodeFromString&lt;Product&gt;(productsJson[index])<br><br>            Row(<br>                Modifier<br>                    .fillMaxWidth()<br>                    .padding(8.dp)<br>            ) {<br><br>                // ❌ Decoding bitmap on every recomposition<br>                val bitmap = BitmapFactory.decodeResource(<br>                    context.resources,<br>                    R.drawable.ic_launcher_background<br>                )<br>                Image(bitmap.asImageBitmap(), contentDescription = null)<br>                Spacer(Modifier.width(8.dp))<br>                Text(product.name)<br>            }<br>        }<br>    }<br>}</pre><p><strong>What’s Wrong Here</strong></p><ul><li><strong>Repeated JSON Parsing</strong> — Data is re-parsed on every recomposition.</li><li><strong>Bitmap Decoding</strong> — Raw bitmaps are decoded repeatedly, a heavy operation.</li><li><strong>Excessive Allocations</strong> — Each scroll or small state change creates new objects.</li></ul><p>In the <strong>Memory Profiler:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Q_uvw06ymTK4FISp_QzPg.png" /></figure><p>You’d see:</p><ul><li><strong>Spikes in allocations</strong> every time the list recomposes.</li><li><strong>Frequent GC events</strong> as old lists are discarded and new ones allocated.</li></ul><p>This cycle — <strong>create → discard → GC → repeat</strong> will leads to unnecessary CPU and memory overhead.</p><p>✅<strong> Good Example (Optimized)</strong></p><pre>@Composable<br>fun GoodProductList(productsJson: List&lt;String&gt;) {<br>    // ✅ Parse JSON once and remember the result<br>    val products = remember {<br>        productsJson.map { Json.decodeFromString&lt;Product&gt;(it) }<br>    }<br><br>    LazyColumn {<br>        items(products.size) { index -&gt;<br>            val product = products[index]<br>            Row(<br>                Modifier<br>                    .fillMaxWidth()<br>                    .padding(8.dp)<br>            ) {<br>                // ✅ Use Coil AsyncImage for caching and scaling<br>                AsyncImage(<br>                    model = R.drawable.ic_launcher_background,<br>                    contentDescription = null,<br>                    modifier = Modifier.size(80.dp)<br>                )<br>                Spacer(Modifier.width(8.dp))<br>                Text(product.name)<br>            }<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SC8v2FSSTLMkivGyQ1njeA.png" /></figure><p><strong>Why This Is Better</strong></p><ul><li><strong>Lower GC Frequency</strong> — Because fewer temporary objects are created, the Garbage Collector runs <strong>less often</strong>, reducing CPU overhead and improving frame stability.</li><li><strong>Stable Memory Graph</strong> — In the Android Studio Memory Profiler, you’ll see a <strong>flatter allocation line</strong> with far fewer spikes compared to the bad implementation.</li></ul><p>This approach keeps memory usage steady, prevents unnecessary GC pauses, and makes scrolling through large lists <strong>smooth and efficient</strong>.</p><h3>Final Thoughts</h3><p>Efficient memory management is critical for <strong>all Android apps</strong>, not just those built with Jetpack Compose.<br>Whether you’re working with traditional Views or modern declarative UIs, tracking memory usage helps you:</p><ul><li><strong>Reduce unnecessary allocations</strong> to keep your app lightweight.</li><li><strong>Lower GC frequency</strong> to avoid frame drops and jank.</li><li><strong>Detect leaks early</strong> before they reach production.</li></ul><p>Tools like <strong>Android Studio Profiler</strong>, LeakCanary, and heap dumps give you visibility into how objects are created, retained, and collected.<br>Profile regularly, optimize where needed, and you’ll deliver apps that stay <strong>fast, stable, and scalable</strong>.</p><blockquote><strong><em>I’m free to discuss any of these points or dive deeper into specific techniques — feel free to share your thoughts or questions in the comments!</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=694399e6586d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Observing StateFlow in Jetpack Compose]]></title>
            <link>https://blog.stackademic.com/observing-stateflow-in-jetpack-compose-94e3aa838515?source=rss-d9a3850dcba0------2</link>
            <guid isPermaLink="false">https://medium.com/p/94e3aa838515</guid>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[kotlin-stateflow]]></category>
            <category><![CDATA[compose-ui]]></category>
            <dc:creator><![CDATA[Ahmed Omara]]></dc:creator>
            <pubDate>Sat, 01 Feb 2025 22:34:40 GMT</pubDate>
            <atom:updated>2025-02-24T02:09:01.091Z</atom:updated>
            <content:encoded><![CDATA[<p>State management is key to building a smooth UI in Jetpack Compose. In this article, we’ll explore different functions that help observe changes in StateFlow and other types of state in Compose.</p><h3>1. collectAsState()</h3><p>collectAsState() converts a StateFlow or Flow into a Compose state that updates automatically whenever the state changes.</p><h3>2. collect() inside LaunchedEffect</h3><p>Unlike collectAsState(), using collect() inside LaunchedEffect does not update the UI automatically. You must manually store the collected value in a state.</p><p><em>Example : </em>Showing Difference between collect and collectAsState:</p><pre>class MainViewModel : ViewModel() {<br>    private val _state = MutableStateFlow(&quot;Idle&quot;) // Initial value is important<br>    val state: StateFlow&lt;String&gt; = _state.asStateFlow()<br>    <br>    init {<br>        fetchData()<br>    }<br><br>    private fun fetchData() {<br>        viewModelScope.launch {<br>            _state.value = &quot;Loading...&quot;<br>            delay(5000)<br>            _state.value = &quot;Data Loaded&quot;<br>            delay(5000)<br>            _state.value = &quot;Finished&quot;<br>        }<br>    }<br>}<br><br>@Composable<br>fun DisplayCollected(modifier: Modifier = Modifier, viewModel: MainViewModel = viewModel()) {<br>    // ✅ Using collectAsState() to automatically update UI when state changes<br>    val state by viewModel.state.collectAsState()<br><br>    // ✅ Using collect() in a LaunchedEffect to manually update another state<br>    var collectedValue by remember { mutableStateOf(&quot;&quot;) }<br><br>    LaunchedEffect(Unit) { // Runs once when the composable is first displayed<br>        viewModel.state.collect { newValue -&gt;<br>            collectedValue = newValue // Manually updating the state<br>        }<br>    }<br><br>    Column {<br>        // 🌟 UI updates automatically with collectAsState()<br>        Text(<br>            modifier = modifier.fillMaxWidth(),<br>            text = &quot;Using collectAsState(): $state&quot;,<br>            textAlign = TextAlign.Center<br>        )<br><br>        // 🌟 UI updates manually using collect() inside LaunchedEffect<br>        Text(<br>            modifier = modifier.fillMaxWidth(),<br>            text = &quot;Using collect() in LaunchedEffect: $collectedValue&quot;,<br>            textAlign = TextAlign.Center<br>        )<br>    }<br>}</pre><h3>3. collectAsStateWithLifecycle()</h3><p>This function behaves like collectAsState() but with additional lifecycle awareness. It stops collecting when the UI is not visible, such as <strong>when the user navigates away.</strong></p><h3>4. snapshotFlow()</h3><p>snapshotFlow() converts a Compose state into a Flow and only emits when the value actually changes.</p><p><em>Example :</em></p><pre>@Composable<br>fun SearchInput() {<br>    var query by remember { mutableStateOf(&quot;&quot;) }<br><br>    LaunchedEffect(Unit) {<br>        snapshotFlow { query }<br>            .collect { searchText -&gt;<br>                Log.d(&quot;SearchInput&quot;, &quot;Searching for: $searchText&quot;)<br>            }<br>    }<br><br>    TextField(<br>        value = query,<br>        onValueChange = { query = it },<br>        label = { Text(&quot;Search&quot;) }<br>    )<br>}</pre><blockquote><strong>Note:</strong> If the same value is assigned repeatedly, snapshotFlow() won’t emit it again, preventing unnecessary updates.</blockquote><h3>5. rememberUpdatedState()</h3><p>rememberUpdatedState() keeps track of the latest state value within side effects like LaunchedEffect without causing unnecessary recompositions.</p><h3>Why Use rememberUpdatedState() ?</h3><p>Without it, LaunchedEffect restarts whenever the state changes, which can lead to unintended behavior.</p><p><em>Example </em>:</p><pre>@Composable<br>fun TimerExample() {<br>    var seconds by remember { mutableStateOf(5) } // Default 5 seconds<br><br>    Column(<br>        modifier = Modifier.fillMaxSize(),<br>        verticalArrangement = Arrangement.Center,<br>        horizontalAlignment = Alignment.CenterHorizontally<br>    ) {<br>        Text(text = &quot;Timer set to: $seconds seconds&quot;, fontSize = 20.sp)<br><br>        Spacer(modifier = Modifier.height(16.dp))<br><br>        Button(onClick = { seconds += 2 }) { // Increase timer dynamically<br>            Text(&quot;Increase Timer&quot;)<br>        }<br><br>        Spacer(modifier = Modifier.height(16.dp))<br><br>        TimerWithoutRememberUpdatedState(seconds) // Restarts on every change<br>        TimerWithRememberUpdatedState(seconds) // Keeps running with latest value<br>    }<br>}<br></pre><pre>❌ Without rememberUpdatedState (Incorrect)<br>@Composable<br>fun TimerWithoutRememberUpdatedState(seconds: Int) {<br>    LaunchedEffect(seconds) { // Restarts every time `seconds` changes<br>        delay(seconds * 1000L)<br>        println(&quot;Without RememberUpdatedState -&gt; Timer finished: $seconds seconds&quot;)<br>    }<br>}</pre><pre>✅ With rememberUpdatedState (Correct)<br>@Composable<br>fun TimerWithRememberUpdatedState(seconds: Int) {<br>    val latestSeconds = rememberUpdatedState(seconds) // Holds the latest value<br><br>    LaunchedEffect(Unit) { // Runs once<br>        delay(latestSeconds.value * 1000L)<br>        println(&quot;With RememberUpdatedState -&gt; Timer finished: ${latestSeconds.value} seconds&quot;)<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*2MNlVb5uhjGtQ7OY0xuZMw.gif" /></figure><h3>Summary:</h3><ul><li><strong>Without </strong><strong>rememberUpdatedState()</strong> → The timer restarts every time seconds changes.</li><li><strong>With </strong><strong>rememberUpdatedState()</strong> → The timer keeps running while always using the latest value.</li></ul><h3>Conclusion</h3><p>Understanding how to observe and manage state effectively in Jetpack Compose can significantly improve your app’s performance and user experience. Use these functions appropriately:</p><p>Function Purpose collectAsState() Automatically updates UI with StateFlow changes collect() in LaunchedEffect Manually updates state from a Flow collectAsStateWithLifecycle() Similar to collectAsState() but lifecycle-aware snapshotFlow() Converts a Compose state into a Flow, emits only on changes rememberUpdatedState() Keeps track of the latest value inside side effects.</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94e3aa838515" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/observing-stateflow-in-jetpack-compose-94e3aa838515">Observing StateFlow in Jetpack Compose</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[State in Compose]]></title>
            <link>https://blog.stackademic.com/state-in-compose-0fd59e7cdc3d?source=rss-d9a3850dcba0------2</link>
            <guid isPermaLink="false">https://medium.com/p/0fd59e7cdc3d</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[flow]]></category>
            <category><![CDATA[jetpack-compose-ui]]></category>
            <category><![CDATA[compose]]></category>
            <dc:creator><![CDATA[Ahmed Omara]]></dc:creator>
            <pubDate>Tue, 28 Jan 2025 22:45:32 GMT</pubDate>
            <atom:updated>2025-02-03T03:02:52.265Z</atom:updated>
            <content:encoded><![CDATA[<p>Before diving into <strong>State in Compose</strong>, it’s important to first understand the different types of states used in Jetpack Compose. There are two main types of states that are commonly used</p><h4>1. Screen UI State</h4><p>This state is used when you need to display data on the UI, or when the business logic changes, it triggers UI updates.</p><p><em>But if we don’t use StateFlow…</em></p><ul><li>The UI will probably just sit there, staring at you like it’s waiting for a bus that never arrives.</li><li>Your users? They’ll be tapping the screen like it’s a magic trick, hoping for something to change. 🤷‍♂️</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*QxMxlZ_YEKVqQUdAjC1n8A.png" /></figure><p><strong>Example</strong>: Using StateFlow to load data from an API and display it on the UI.</p><pre>// Define the state as a StateFlow<br>private val _dataState = MutableStateFlow&lt;Result&lt;String&gt;&gt;(Result.Loading)<br>val dataState: StateFlow&lt;Result&lt;String&gt;&gt; = _dataState<br><br>// Function to load data<br>fun loadData() {<br>    viewModelScope.launch {<br>        // Simulate a network or database operation<br>        _dataState.value = Result.Loading<br>        try {<br>            val data = fetchDataFromNetwork()<br>            _dataState.value = Result.Success(data)<br>        } catch (e: Exception) {<br>            _dataState.value = Result.Error(e)<br>        }<br>    }<br>}</pre><h4>2. Element UI State</h4><p>This state refers to characteristics of individual UI elements. For instance, managing the value of a TextField, toggling the visibility of an element, or enabling/disabling a button based on the current state.</p><p><strong>Example</strong>: Managing the state of a TextField and enabling a button based on its input.</p><pre>@Composable<br>fun InputForm() {<br>    // State to store the text input<br>    var text by remember { mutableStateOf(&quot;&quot;) }<br>    <br>    // State to enable/disable the submit button based on text input<br>    val isSubmitEnabled = text.isNotEmpty()<br><br>    Column(<br>        modifier = Modifier.padding(16.dp)<br>    ) {<br>        TextField(<br>            value = text,<br>            onValueChange = { newText -&gt;<br>                text = newText // Updates text state<br>            },<br>            label = { Text(&quot;Enter something&quot;) }<br>        )<br>        <br>        Spacer(modifier = Modifier.height(16.dp))<br><br>        Button(<br>            onClick = { /* Handle submit action */ },<br>            enabled = isSubmitEnabled // Button is enabled only if text is not empty<br>        ) {<br>            Text(&quot;Submit&quot;)<br>        }<br>    }<br>}</pre><p>In this example:</p><ul><li>We use a TextField to accept user input, and its value is bound to the text state.</li><li>The <strong>submit button</strong> is enabled only when the text state is not empty (isSubmitEnabled).</li><li>As the user types in the TextField, the state is updated using onValueChange.</li></ul><h3>State Management in Compose: State Hoisting</h3><p>To manage state across composables in a predictable and testable way, <strong>State Hoisting</strong> is commonly used. This is a design pattern that allows state to be moved up to a higher-level composable and passed down to child composables.</p><h4>How State Hoisting Works:</h4><ol><li><strong>Move the state to a higher-level composable</strong>: The parent composable will own the state.</li><li><strong>Pass the state down to the child composable</strong>: The state and a function to update it are passed as parameters.</li></ol><p><strong>Example</strong>:</p><pre>var text by remember { mutableStateOf(&quot;&quot;) } // State is hoisted here<br><br>ChildComposable(<br>    value = text,<br>    onValueChange = { newText -&gt;<br>        text = newText // Update state from child composable<br>    }<br>)</pre><h3>Manage State Using Jetpack Compose Functions</h3><p>Managing state in Jetpack Compose involves using a set of functions that help store and manipulate values efficiently:</p><ol><li><strong>remember</strong>: Stores an object in memory across recompositions, so it doesn’t get recreated each time the composable is recomposed.</li><li><strong>mutableStateOf</strong>: Creates a state variable. When the value of the state changes, it triggers a recomposition of the composable that reads this state.</li></ol><pre>val counter = remember { mutableStateOf(0) }<br>Button(onClick = { counter.value++ }) {<br>    Text(&quot;Count: ${counter.value}&quot;)<br>}</pre><p>3. <strong>rememberSaveable</strong>: Similar to remember, but specifically used for state values that need to survive lifecycle events such as configuration changes (e.g., screen rotations).</p><pre>val counter = rememberSaveable { mutableStateOf(0) }<br>Button(onClick = { counter.value++ }) {<br>    Text(&quot;Count: ${counter.value}&quot;)<br>}</pre><p><strong>4. derivedStateOf</strong>: Creates a state that is derived from other state variables. This allows automatic updates when the dependent states change.<br>Example:</p><pre>val number = remember { mutableStateOf(5) }<br>val isEven = derivedStateOf { number.value % 2 == 0 }<br><br>Text(&quot;Is the number even? ${isEven.value}&quot;)<br>Button(onClick = { number.value++ }) {<br>    Text(&quot;Increase Number&quot;)<br>}</pre><blockquote><strong>Unlike </strong><strong>mutableStateOf, </strong><strong>derivedStateOf is updated automatically when the source state changes.</strong></blockquote><p>5. <strong>snapshotFlow</strong>: Converts a state into a flow, allowing you to collect the state changes asynchronously in a coroutine.</p><pre>val counter = remember { mutableStateOf(0) }<br>LaunchedEffect(counter.value) {<br>    snapshotFlow { counter.value }<br>        .collect { value -&gt;<br>            Log.d(&quot;SnapshotFlow&quot;, &quot;State changed: $value&quot;)<br>        }<br>}<br>Button(onClick = { counter.value++ }) {<br>    Text(&quot;Count: ${counter.value}&quot;)<br>}</pre><p>6. <strong>LaunchedEffect(key)</strong>: Designed to run suspend functions inside Compose. The block inside LaunchedEffect is executed whenever the value of the provided key changes.</p><pre>val counter = remember { mutableStateOf(0) }<br>LaunchedEffect(counter.value) {<br>    // Trigger a suspend function whenever counter changes<br>    delay(1000)<br>    Log.d(&quot;LaunchedEffect&quot;, &quot;Counter value: ${counter.value}&quot;)<br>}<br>Button(onClick = { counter.value++ }) {<br>    Text(&quot;Increment&quot;)<br>}</pre><p>7. <strong>SideEffect</strong>: Code inside SideEffect is guaranteed to run after the composition is completed. It’s useful for triggering side effects after Compose has finished handling the UI updates.</p><pre>val counter = remember { mutableStateOf(0) }<br>SideEffect {<br>    Log.d(&quot;SideEffect&quot;, &quot;Counter updated: ${counter.value}&quot;)<br>}<br>Button(onClick = { counter.value++ }) {<br>    Text(&quot;Increase Counter&quot;)<br>}</pre><h3>Conclusion: Best Practices for State Management in Jetpack Compose</h3><p>State management is a core concept in Jetpack Compose, and understanding how to handle state effectively is essential for building performant and responsive UIs. Here are a few best practices to keep in mind:</p><ol><li><strong>Minimize State in Composables</strong>: While it’s tempting to manage all state within a composable, it’s better to hoist state when possible. This makes your composables more reusable and easier to test.</li><li><strong>Leverage </strong><strong>derivedStateOf for Computed State</strong>: When creating states that depend on other states, prefer using derivedStateOf. This eliminates the need for manually updating the derived state, making the code simpler and less error-prone.</li><li><strong>Optimize Recomposition with </strong><strong>remember and </strong><strong>mutableStateOf</strong>: Avoid unnecessary recompositions by using remember to store state, and mutableStateOf for state variables that trigger recompositions. Keep in mind that frequent recompositions can impact your app’s performance.</li><li><strong>Use Flows for Asynchronous Data</strong>: When working with asynchronous data, use StateFlow or snapshotFlow to collect data changes efficiently. These allow you to manage real-time updates and make your UI more dynamic and interactive.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*ccP9oxPJD4PAF4Oz" /></figure><blockquote>By following these practices and using the right state management functions, you can create highly performant and scalable applications with Jetpack Compose. <br>State management is powerful, but it’s important to understand how each function behaves to avoid over-complicating your codebase and ensure that your UI stays reactive and responsive.</blockquote><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0fd59e7cdc3d" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/state-in-compose-0fd59e7cdc3d">State in Compose</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Multiplatform Navigation with Decompose]]></title>
            <link>https://blog.stackademic.com/mastering-multiplatform-navigation-with-decompose-fe077135e695?source=rss-d9a3850dcba0------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe077135e695</guid>
            <category><![CDATA[decompose]]></category>
            <category><![CDATA[kmm]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Ahmed Omara]]></dc:creator>
            <pubDate>Mon, 11 Nov 2024 14:12:36 GMT</pubDate>
            <atom:updated>2024-11-14T02:40:32.313Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_0QINhOfC4lvvT4e.png" /></figure><p>Decompose is a Kotlin Multiplatform library that simplifies navigation and state management across iOS and Android applications, allowing for consistent, shared logic across platforms.</p><h3>Why Choose Decompose?</h3><ol><li><strong>Pluggable, Platform-Specific UI</strong><br>Decompose integrates smoothly with different platform-specific UIs (such as Compose for Android, SwiftUI for iOS, and Kotlin/React for the web), giving developers flexibility to create native interfaces while sharing logic.</li><li><strong>Shared Navigation Logic</strong><br>With Decompose, you can write navigation logic once and apply it across both Android and iOS, making it easier to maintain consistency and reduce code duplication.</li><li><strong>Lifecycle-Aware Components</strong><br>Each component in Decompose is aware of its own lifecycle, meaning it can manage its state independently based on its visibility and activity.</li><li><strong>Persistent Back Stack</strong><br>Components in Decompose remain active in the back stack even when navigated away from, improving performance and making it quick to return to previous screens.</li></ol><h3>Components in Decompose</h3><p>Before diving into code, let’s break down the main components used in Decompose:</p><ul><li><strong>ComponentContext</strong><br>Manages the lifecycle of each component, allowing you to observe lifecycle events like ON_CREATE and ON_DESTROY. It&#39;s similar to Context or LifecycleOwner in Android.</li><li><strong>Value</strong><br>Acts as a state holder, returning the current state (similar to State, StateFlow, or LiveData in Android).</li><li><strong>ChildStack</strong><br>Manages navigation between components using actions like push, pop, and replace.</li><li><strong>StackNavigation</strong><br>Holds the current configuration being displayed, making navigation management easy.</li></ul><h3>Step 1: Define RootComponentChild</h3><p>This sealed class represents the different child screens/components your root component can display. In this case, there are two child components: ListChild and DetailsChild.</p><pre>sealed class RootComponentChild {<br>    class ListChild(val component: ListComponent) : RootComponentChild()<br>    class DetailsChild(val component: DetailsComponent) : RootComponentChild()<br>}</pre><h3>Step 2: Define the Root Component Interface</h3><p>This interface describes the main functions and properties of the root component, including the navigation stack and the methods to handle navigation and back actions.</p><pre>interface RootComponent {<br>    val childStack: Value&lt;ChildStack&lt;*, RootComponentChild&gt;&gt;<br>    <br>    fun onBackPressure()<br>    fun navigateToDetails(item: Model)<br>}</pre><h3>Step 3: Implement the Root Component</h3><p>The DefaultRootComponent class implements RootComponent and uses ComponentContext to manage the lifecycle. It also utilizes StackNavigation to handle navigation between child screens (List and Details).</p><pre>class DefaultRootComponent(<br>    private val componentContext: ComponentContext,<br>    private val homeViewModel: HomeViewModel<br>) : RootComponent, ComponentContext by componentContext {<br><br>    // StackNavigation holds the navigation stack<br>    private val navigation = StackNavigation&lt;RootComponentConfiguration&gt;()<br><br>    // The child stack that represents the current and past screens<br>    override val childStack: Value&lt;ChildStack&lt;*, RootComponentChild&gt;&gt; = childStack(<br>        source = navigation,<br>        serializer = RootComponentConfiguration.serializer(),<br>        initialConfiguration = RootComponentConfiguration.List,<br>        handleBackButton = true,<br>        childFactory = ::childFactory,<br>    )<br><br>    // Factory to create child components based on configuration<br>    private fun childFactory(<br>        rootComponentConfiguration: RootComponentConfiguration,<br>        componentContext: ComponentContext<br>    ): RootComponentChild {<br>        return when (rootComponentConfiguration) {<br>            is RootComponentConfiguration.List -&gt; RootComponentChild.ListChild(<br>                DefaultListComponent(<br>                    componentContext = componentContext,<br>                    homeViewModel = homeViewModel,<br>                    onClicked = ::navigateToDetails<br>                )<br>            )<br>            is RootComponentConfiguration.Details -&gt; RootComponentChild.DetailsChild(<br>                DefaultDetailsComponent(<br>                    componentContext = componentContext,<br>                    onBack = ::onBackPressure,<br>                    item = rootComponentConfiguration.item<br>                )<br>            )<br>        }<br>    }<br><br>    // Handle the back button action<br>    override fun onBackPressure() {<br>        navigation.pop()<br>    }<br><br>    // Navigate to the details screen<br>    override fun navigateToDetails(item: Picsum) {<br>        navigation.push(RootComponentConfiguration.Details(item))<br>    }<br><br>    // Configurations for the stack, defining the possible screens<br>    @Serializable<br>    sealed interface RootComponentConfiguration {<br>        @Serializable<br>        data object List : RootComponentConfiguration<br>        @Serializable<br>        data class Details(val item: Picsum) : RootComponentConfiguration<br>    }<br>}</pre><h3>Step 4: Define RootContent for UI</h3><p>This Composable displays the appropriate UI based on the current active child component.</p><pre>@Composable<br>fun RootContent(<br>    component: RootComponent<br>) {<br>    Children(<br>        stack = component.childStack,<br>        modifier = Modifier.fillMaxSize(),<br>        animation = stackAnimation(fade())<br>    ) {<br>        when (val child = it.instance) {<br>            is RootComponentChild.ListChild -&gt; ListContent(child.component)<br>            is RootComponentChild.DetailsChild -&gt; DetailsContent(child.component)<br>        }<br>    }<br>}</pre><h3>Step 5: Create the Preview</h3><pre>@Composable<br>@Preview<br>fun App(root: DefaultRootComponent) {<br>    MaterialTheme {<br>        RootContent(root)<br>    }<br>}</pre><p>You can check the full code for this project on <a href="https://github.com/AhmedOmara14/Decompose-KMM"><strong>GitHub</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*fbbmge0vhenNtBen" /></figure><h4>Resources</h4><ul><li><a href="https://arkivanov.github.io/Decompose/">Decompose Documentation</a></li></ul><p><strong>Connect with Me: </strong><a href="https://www.linkedin.com/in/ahmed-omara-546955187/">Ahmed Omara | LinkedIn</a></p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe077135e695" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/mastering-multiplatform-navigation-with-decompose-fe077135e695">Mastering Multiplatform Navigation with Decompose</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>