<?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 Pavel Bo on Medium]]></title>
        <description><![CDATA[Stories by Pavel Bo on Medium]]></description>
        <link>https://medium.com/@pavelbo?source=rss-582b5f46adf3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tERdU6p-mXdpduyv-TPOew.jpeg</url>
            <title>Stories by Pavel Bo on Medium</title>
            <link>https://medium.com/@pavelbo?source=rss-582b5f46adf3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 04:01:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pavelbo/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[How to Avoid Recomposition Loops in Jetpack Compose]]></title>
            <link>https://medium.com/@pavelbo/how-to-avoid-recomposition-loops-in-jetpack-compose-9bc65882a15f?source=rss-582b5f46adf3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bc65882a15f</guid>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Pavel Bo]]></dc:creator>
            <pubDate>Thu, 14 Nov 2024 20:37:02 GMT</pubDate>
            <atom:updated>2024-11-14T20:37:50.790Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mdOFUUhWeB6toZGf" /><figcaption>Photo by <a href="https://unsplash.com/@tine999?utm_source=medium&amp;utm_medium=referral">Tine Ivanič</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Jetpack Compose is a powerful tool that simplifies creating UIs in Android, but it also presents a learning curve for developers. Many encounter unexpected behavior and issues that may not seem obvious at first glance. In this article, we’ll look at one such issue — how to prevent recomposition from getting stuck in a loop in Compose.</p><h3>Example Code</h3><p>Let’s start with an example:</p><pre>data class MyDataClass(  <br>    val i: Int = 0,  <br>    val block: () -&gt; Unit = {},  <br>)<br><br>class MyScreenViewModel : ViewModel() {<br>    private val dataSource = MutableSharedFlow&lt;Int&gt;(1)<br><br>    val stateValue: StateFlow&lt;MyDataClass&gt;<br>        get() = dataSource<br>            .map { number -&gt; <br>                MyDataClass(number, { println(&quot;Hello, World!&quot;) }) <br>            }<br>            .stateIn(viewModelScope, SharingStarted.Eagerly, MyDataClass())<br>}<br><br>@Composable  <br>fun MyScreen(viewModel: MyScreenViewModel) {  <br>    Log.d(&quot;[TAG]&quot;, &quot;Recomposition!&quot;)<br><br>    val state by viewModel.stateValue.collectAsStateWithLifecycle()<br>    val checked = remember { mutableStateOf(false) }  <br><br>    Column {  <br>        Checkbox(<br>            checked = checked.value,<br>            onCheckedChange = { isChecked -&gt; checked.value = isChecked }<br>        )<br>        Text(&quot;state: ${state.i}&quot;)<br>    }<br>}</pre><p>At first glance, this code seems fine. But if you run it, toggle the checkbox, and check <strong>LogCat</strong> or <strong>Layout Inspector</strong>, you’ll see that recomposition is stuck in a loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*lV_VSkYrN8O36l_eV37bwA.gif" /><figcaption>Recomposition Loops</figcaption></figure><p>Why does this happen? Let’s investigate.</p><h3>Understanding the Problem</h3><p>The core of the problem lies in the <em>collectAsStateWithLifecycle()</em> extension function. Here’s what it looks like under the hood:</p><pre>@Composable  <br>fun &lt;T&gt; Flow&lt;T&gt;.collectAsStateWithLifecycle(<br>    initialValue: T,<br>    lifecycle: Lifecycle,<br>    minActiveState: Lifecycle.State = Lifecycle.State.STARTED,<br>    context: CoroutineContext = EmptyCoroutineContext<br>): State&lt;T&gt; {<br>    return produceState(initialValue, this, lifecycle, minActiveState, context) {<br>        lifecycle.repeatOnLifecycle(minActiveState) {<br>            if (context == EmptyCoroutineContext) {<br>                this@collectAsStateWithLifecycle.collect { this@produceState.value = it }<br>            } else withContext(context) {<br>                this@collectAsStateWithLifecycle.collect { this@produceState.value = it }<br>            }<br>        }<br>    }<br>}<br><br>@Composable  <br>fun &lt;T&gt; produceState(  <br>    initialValue: T,  <br>    vararg keys: Any?,  <br>    producer: suspend ProduceStateScope&lt;T&gt;.() -&gt; Unit  <br>): State&lt;T&gt; {  <br>    val result = remember { mutableStateOf(initialValue) }  <br>    @Suppress(&quot;CHANGING_ARGUMENTS_EXECUTION_ORDER_FOR_NAMED_VARARGS&quot;)  <br>    LaunchedEffect(keys = keys) {  <br>        ProduceStateScopeImpl(result, coroutineContext).producer()  <br>    }  <br>    return result  <br>}</pre><p>The function creates a Compose state and subscribes to the flow using <em>LaunchedEffect</em>, allowing us to observe new values emitted by the flow.</p><p>So, now we can see two key issues in our code:</p><ol><li>Each time we access <em>stateValue</em>, a new <em>StateFlow</em> instance is created because the <em>get()</em> block in <em>stateValue</em> re-evaluates, which leads to a new <em>LaunchedEffect</em> being triggered in <em>collectAsStateWithLifecycle()</em> and a new subscription being added;</li><li>Each new <em>StateFlow</em> instance creates a new <em>MyDataClass</em> instance, which, despite being a <em>data class</em>, is not comparable due to the lambda function inside it. Consequently, Compose treats each new instance as a distinct value, triggering a recomposition.</li></ol><h3>Why Lambdas Are Not Comparable</h3><p>A simple expression like:</p><pre>{ println(&quot;Hello, World!&quot;) } != { println(&quot;Hello, World!&quot;) }</pre><p>may look surprising but illustrates the issue here. Lambdas in Kotlin are instances of <em>Function</em><strong><em>X</em></strong> interfaces (where <strong><em>X</em></strong> represents the number of parameters). Thus, two <em>Function</em><strong><em>X</em></strong> instances are only considered equal by reference, not by content.</p><pre>// An example of a FunctionX: Function3 with 3 input parameters<br><br>public interface Function3&lt;in P1, in P2, in P3, out R&gt; : kotlin.Function&lt;R&gt; {  <br>    public abstract operator fun invoke(p1: P1, p2: P2, p3: P3): R  <br>}</pre><h3>Solution</h3><p>To fix this problem, we have two options:</p><ol><li><strong>Exclude the lambda from </strong><em>equals</em><strong> and </strong><em>hashCode</em><strong> calculations in MyDataClass.</strong> This prevents unnecessary recompositions by ensuring <em>MyDataClass(1, {})</em> objects are seen as equal;</li><li><strong>Make </strong><em>stateValue</em><strong> stable</strong> by avoiding the re-evaluation of the <em>get()</em> function, so it does not create a new <em>StateFlow</em> instance on each access.</li></ol><p>The most optimal solution is to combine both approaches, as shown below:</p><pre>data class MyDataClass(  <br>    val i: Int = 1,  <br>    val block: () -&gt; Unit = {},  <br>) {  <br>    override fun equals(other: Any?): Boolean {  <br>        if (this === other) return true  <br>        if (javaClass != other?.javaClass) return false  <br><br>        other as MyDataClass  <br>        return i == other.i  <br>    }  <br><br>    override fun hashCode(): Int {  <br>        return i  <br>    }  <br>}<br><br>class MyScreenViewModel : ViewModel() {<br>    private val dataSource = MutableSharedFlow&lt;Int&gt;(1)<br><br>    val stateValue: StateFlow&lt;MyDataClass&gt; = dataSource<br>        .map { number -&gt; MyDataClass(number, { println(&quot;Hello, World!&quot;) }) }<br>        .stateIn(viewModelScope, SharingStarted.Eagerly, MyDataClass())<br>}</pre><blockquote>Thank you for reading! If you found this article helpful, please give it an applaud and share your thoughts in the comments. Your feedback helps me improve!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bc65882a15f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>