<?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 AmirHossein Ghafoorian on Medium]]></title>
        <description><![CDATA[Stories by AmirHossein Ghafoorian on Medium]]></description>
        <link>https://medium.com/@amirhgh1377?source=rss-e62a1b4ae677------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*jyr0NVy2nK2XPL6i</url>
            <title>Stories by AmirHossein Ghafoorian on Medium</title>
            <link>https://medium.com/@amirhgh1377?source=rss-e62a1b4ae677------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 23:18:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amirhgh1377/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[Recomposition problem with mutations]]></title>
            <link>https://medium.com/@amirhgh1377/recomposition-problem-with-mutations-f82f7abafe56?source=rss-e62a1b4ae677------2</link>
            <guid isPermaLink="false">https://medium.com/p/f82f7abafe56</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[AmirHossein Ghafoorian]]></dc:creator>
            <pubDate>Tue, 10 Jan 2023 19:13:31 GMT</pubDate>
            <atom:updated>2023-01-10T19:13:31.314Z</atom:updated>
            <content:encoded><![CDATA[<h4>Here are some recomposition problems which you might face and their solutions.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CCDT-6Lk9n3uBTz6JeKjvQ.jpeg" /></figure><p>Jetpack Compose is Android’s modern declarative UI Toolkit for building native UI. Declarative in this case means you describe how your UI should look rather than what it should be.</p><p>What we mean by how rather than what, is that in XML style, you define your views and get a reference (binding, findviewbyId, … ) from them in your activity, fragment or etc, then use them within your logic and at certain conditions, change them as you wish.</p><p>But what we do in compose is we describe our Kotlin-style composable functions and pass them some states. Then we manipulate our states either in parent composables (UI logic) or viewModels (Business logic). Finally, composables <strong>react</strong> to these manipulations.</p><p>This reaction is called <strong>Recomposition</strong>. To better say the compose compiler re-executes composable functions which have been changed, while it ignores those ones which is <strong>sure</strong> haven’t been changed (notice the word sure, we will talk about it later in this article).</p><p>The problem is, these manipulations may sometimes lead to unexpected behavior.</p><p>In this article we delve into problematic scenarios with recomposition, then we propose how to fix them.</p><p>For demonstration, we are going to have a MVI architecture for our example.</p><h3><strong>List</strong></h3><p>Having a list in your UI and trying to mutate it, is a common way to face recomposition problem. let&#39;s see what is the problem and how we can prevent it to happen.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d1516b73efa0ad172362fd0062b3ef3/href">https://medium.com/media/5d1516b73efa0ad172362fd0062b3ef3/href</a></iframe><p>In this example, we have a list as our UI state and we are observing it in our composable. Whenever one of the buttons is clicked, an action will be sent to the ViewModel and calls one of our list mutation functions accordingly. We expect to <strong>Observe</strong> any changes to the list in our composable and trigger a recomposition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*C_VdV7Ia6dQ5x6UhynhF3A.png" /></figure><p>If you try this, you will see that none of the buttons can make any visual changes in the list of cars, although it changes the value of the UI State in the ViewModel.</p><p>This is because the compose compiler can not <strong>track</strong> list mutations and react accordingly. In other words, it does not even notice any changes ever happening to the list UI State.</p><h4>Solution</h4><p>There are 2 ways to solve this issue.</p><p>1 — Make sure you change the <strong>instance </strong>of the list. To this end, simply just change the mutation functions in the ViewModel like either one of these approaches:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b10901d95639602c35e7bed729ccc3fc/href">https://medium.com/media/b10901d95639602c35e7bed729ccc3fc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*l8BK4IT1rgnHLUOVhBd_ZA.png" /></figure><p>Now the instance of the list (as UI State) is changing and compose compiler gets notified for sure and will trigger a recomposition.</p><p>2 — Compose SDK has provided a version of <strong>mutableListOf</strong> that can be tracked by compose compiler and it is called <strong>mutableStateListOf</strong>. Therefore, the only thing you have to do is when you want to create an instance of your list for the first time, use mutableStateListOf instead of mutableListOf.</p><h3>Map</h3><p>MutableMap can be treated like MutableList in this context. We define our mutation functions for map UI State.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38c4a3ccf5dc7639f855cb9da330f665/href">https://medium.com/media/38c4a3ccf5dc7639f855cb9da330f665/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*mZXWPWxTk37P-aqc3vTkMw.png" /></figure><p>If you also try this approach, you will see that just like our list example, clicking the buttons does not make any visual changes.</p><p><strong>Solution</strong></p><p>1 — The instance of the map should be changed just like we did in the List section.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9928715f4089aff596dffbc318e9ed67/href">https://medium.com/media/9928715f4089aff596dffbc318e9ed67/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*DyphU7sBhP5VEFFotNImwA.png" /></figure><p>2 — There is also an observable version of mutableMapOf provided in compose called <strong>mutableStateMapOf</strong><em>. </em>Simply use this where you want to create your map instance.</p><h3>Data class</h3><p>Mutating data classes can also lead to recomposition problems. In this example, we have a data class as our UI State which contains 3 items with String type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c33b676a0af5d4c7f83fffd19401197b/href">https://medium.com/media/c33b676a0af5d4c7f83fffd19401197b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*VQvaI2OCCIIe2giUACLf0Q.png" /></figure><p>Here, Clicking the first button will not cause any change in the UI; but if you click the second button, it updates the UI. The reason is that we are actually assigning a <strong>new instance</strong> to the UI State (which is a data class) in the changeSecondElement function in viewModel, and compose compiler can clearly observe this change and react to it by causing a recomposition, while the changeFirstElement function only mutates the UI State and this is not tracked by compose compiler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*IpM03Q8abs0A6OLOGTm8uQ.png" /></figure><blockquote>If you click the first button and then the second button, you see both first and second elements have changed. That’s because clicking the first function surely made a change into the UI State but it didn’t trigger a recomposition; second button triggers a recomposition and it leads to updating all changed variables and the composable functions depending on them.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*W2LmLPCW1a0clTpjo7CMRw.png" /></figure><p>You can use <strong>update</strong> function to set a new instance to your MutableStateFlow.</p><p>Also using <strong>copy </strong>function for data class will help you to create a new copy of your data class and only change the fields you want.</p><p>After applying these 2 tips to our mutation functions, they will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a7a08d8c21e4d65aca072abce3c3ca3/href">https://medium.com/media/1a7a08d8c21e4d65aca072abce3c3ca3/href</a></iframe><blockquote>A common mistake in this case is that we assume calling copy function will update the instance; Its wrong because it only creates a copy of your data class but does not assign a new instance to it.</blockquote><p>There is no state version for data classes like mutableStateListOf and mutableStateMapOf to be tracked by compose compiler. You should always remember to update your data class instance.</p><blockquote>Not even mutableStateOf(MyDataClass(…)) will help you in this case.</blockquote><h3>Bonus</h3><p>Earlier in this article, we said that recomposition means compose compiler re-executes those composable functions which have been changed, and ignores those which is <strong>sure</strong> haven’t changed. However, what do we mean by sure? In which conditions compose compiler is sure and in which it isn’t? In this section, we are going to talk about this.</p><p>There is a trade-off for compose compiler; It chooses stability over performance. This means it chooses to <strong>always </strong>be right and have less performance instead of <strong>sometimes</strong> being right and having better performance.</p><p>In other words, when a recomposition happens, in situations that compose compiler is not sure about whether the passed parameter to a child composable has changed or not, it chooses to recompose it and doesn’t skip it.</p><p>The way compose compiler can be sure about some parameters is by having a <strong>‘Stable’ </strong>annotation with the class. This annotation is added automatically by compose compiler on your Immutable classes passed to composable.</p><p>This means if you pass a data class to a composable that only contains “Val” variables, it is annotated with Stable; but if at least one of them is a “var”, then it will not be annotated with Stable.</p><p>This might seem a bit confusing because, from the beginning of this article, we are complaining about compose compiler ignoring our mutations and not triggering a recomposition. Now we are saying that it has a behavior like an over-recomposition. let&#39;s see an example of this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a9e13da42985e6d195b46383dc123d2/href">https://medium.com/media/8a9e13da42985e6d195b46383dc123d2/href</a></iframe><p>As you see, we are passing a String type parameter (which compose compiler can be sure about it) to our CarItem composable function.</p><p>Now let&#39;s click the first button and change the first element of our UI State data class subsequently. See what happens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*xRQdiKvBu-wxlpQmpkdyrA.png" /></figure><p>As you witness, two of the CarItem’s are skipping the recomposition, because compose compiler is sure that their parameters haven’t been changed.</p><p>Now let&#39;s make some changes to the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9cee497b05390518f4c4ac25a2d6052e/href">https://medium.com/media/9cee497b05390518f4c4ac25a2d6052e/href</a></iframe><p>We have changed the passing parameter type to CarItem from String to MyItem which is a data class that contains a var variable and makes compose compiler not sure about it.</p><p>We do the same test and click the first button. Let&#39;s see what happens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*2KmlxGSu6t2M_sA3kd66xg.png" /></figure><p>Only the first element changes whereas all our CarItem functions got recomposed. That’s because compose compiler was not sure whether they have been changed or not.</p><p>The point of all this is that mutations to data classes don’t trigger a recomposition, but once it does(by assigning a new instance) it recomposes all composable functions depending on that data class.</p><p>For more details about this topic, check out <strong>Jetpack Compose Stability Explained </strong>by<strong> Ben Trengrove.</strong></p><p><a href="https://medium.com/androiddevelopers/jetpack-compose-stability-explained-79c10db270c8">Jetpack Compose Stability Explained</a></p><h3>Summary</h3><ul><li>Always remember to update the instance of your UI State instead of mutating it.</li><li>To reach better performance with your compositions, try to use Immutable data structures.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f82f7abafe56" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>