<?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 Jean Tuffier on Medium]]></title>
        <description><![CDATA[Stories by Jean Tuffier on Medium]]></description>
        <link>https://medium.com/@JeanTuffier?source=rss-6c34490521e4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Nq3lxFtU-ZTYjMuNENurSw.jpeg</url>
            <title>Stories by Jean Tuffier on Medium</title>
            <link>https://medium.com/@JeanTuffier?source=rss-6c34490521e4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:15:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@JeanTuffier/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[Reverse engineering the Bluetooth protocol on Android]]></title>
            <link>https://proandroiddev.com/reverse-engineering-the-bluetooth-protocol-on-android-680275f129e0?source=rss-6c34490521e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/680275f129e0</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Jean Tuffier]]></dc:creator>
            <pubDate>Fri, 29 May 2026 22:29:05 GMT</pubDate>
            <atom:updated>2026-06-29T19:07:40.771Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5NimUAFePNbC38bpOmT3QA.png" /><figcaption>Screenshot of Bluetooth address investigation</figcaption></figure><p>Do you know how Bluetooth networking works? The protocol is used almost everywhere in our modern lives but most people don’t give it a second thought. Including me, until it was too late. This is a story about how a seemingly harmless device upgrade threatened my team’s Christmas holidays. And how we managed our way through networking and security issues, quick UX fixes, and hacky shell commands.</p><h3>Things fall apart</h3><p>I’m part of Entur’s Onboard team. We’re in charge of making the apps used by thousands of people working in the public transportation sector, along with providing the required hardware. Those apps communicate with an external bank terminal over Bluetooth to sell tickets, print reservations, etc. For the past few months, we’ve been rolling out a device upgrade from a single model running on Android 9 to several newer ones running on Android 14 and later. But the first users who received the upgrade were in for a surprise. They couldn’t connect to their Bluetooth devices anymore. One of our apps became completely useless and we entered an all-hands-on-deck emergency.</p><h3>From excitement to anxiety</h3><p>Let’s go back to the end of November 2025, the excitement in the team is high because we just received the long awaited new devices. The whole team test them out to check if all the features work. As expected, they run faster and silky smooth. So we start rolling them out in production. A few days pass and we get our first feedback, all saying the same thing : it’s really difficult to get the app talking with the bank terminal. <a href="https://medium.com/entur/the-code-nobody-wanted-to-change-df2b6df8b7b4">Again?!</a> (we had a similar problem a few month ago) The holiday season is approaching, the excitement from a few days ago turns to anxiety, we don’t want to have an emergency situation right in the middle of Christmas.</p><h3>The problem</h3><p>It’s now early December, and one of our developers runs the app on his test phone. Everything works fine, but after something like 15 minutes, nothing works. Every single login attempt he sends to the terminal times out with a “connect fail” message. That’s odd. He checks which IP is used by the bank terminal, and that’s when he discovers the problem : the bank terminal is using another IP than the hard-coded one we have in the app. We get in touch with some of the users that reported having issues and ask them to check. All of them say that their bank terminal uses a different address.</p><p>The terminal comes with an SDK that requires its IP address to establish the connection with the smart phone. When using the old android 9 devices, the terminal’s IP is always the same, 192.168.44.44. So it makes sense that the app doesn’t manage to connect with the terminal if our users say the IP they see in the settings page of the terminal is something else.</p><p>But the main problem is that we don’t know why it’s not the same anymore. Christmas is just days away, so we decide to go for a temporary solution. The bank terminal can show a QR code that contains the IP address it’s using, by scanning it, our users can reinitialize the connection. Not very user-friendly but it works. We roll out the last hotfix release of the year, our users can work normally, and we have more time to figure out what’s going on. Christmas holidays are saved!</p><h3>Down the rabbit hole</h3><p>By early January, we have our QR code fix in place and confirmation that it works well. However, we are nowhere closer to understanding why the IP keeps changing randomly. At that point I’ve been reading about the Bluetooth protocol on and off without finding much. But one day, one link leading to another, I go down the rabbit hole until I land on the AOSP changelog for Android 10 and 12. And there, in black and white, is the answer: MAC randomization behavior.</p><p>To prevent third-party software of tracking MAC and IP addresses, <a href="https://source.android.com/docs/whatsnew/android-10-release#mac_randomization_enhancements">Android 10</a> enables MAC randomization for client mode, SoftAp, and Wi-Fi Direct. And <a href="https://source.android.com/docs/whatsnew/android-12-release#mac-randomization">Android 12</a> introduces the concept of “non-persistent” randomization. That means Android assigns a new MAC address to your device at the start of every connection.</p><p>The hard-coded IP address used to initialize the SDK at startup on Android 9 is not relevant anymore. The subtle changes in Android 12 about randomization at the start of every connection introduces even more friction for our users. Nobody on the team thought of turning off their device between tests, while almost all of our users turn theirs off after each shift. Which results in a MAC address change, and the IP address with it.</p><p>Because of this, our users need to scan the QR code containing the IP address every time the phone is restarted. We need a way to find which IP is given to the terminal at runtime instead.</p><h3>The android network interfaces</h3><p>Android provides APIs with network interface information. The ConnectivityManager class can show details on WiFi, Bluetooth and Bluetooth tethering networks. But there’s a major limitation : after the Android 9 version, Google does not let third party apps get access to MAC or IP addresses.</p><p>While experimenting, we notice that we can get the IP address with the cli command adb shell ip addr show bt-pan from our computers. The “bt-pan” (Bluetooth Personal Area Network) argument is to limit the results to the Bluetooth tethering interface. It outputs like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JiMXNI1yRzZqBAX1C2S4yA.png" /><figcaption>The adb shell command and its result</figcaption></figure><p>The interesting bit is “inet 10.119.167.81”, that’s the IP address we need to initialize the bank terminal SDK. But Android 14 doesn’t let you run the command ip addr show bt-pan at runtime and crashes with an exception (“adb shell” is only necessary when running the command from a computer on a connected device). Another cli command that could be used is “ip neighbor show” but it’s also forbidden by Google. It’s the same problem that we got earlier with the regular Android APIs.</p><h3>The ARP file</h3><p>Another possibility is to read the ARP file located at “/proc/net/arp”.</p><blockquote>ARP stands for Address Resolution Protocol. The primary function of this protocol is to resolve the IP address of a system to its mac address.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5NimUAFePNbC38bpOmT3QA.png" /><figcaption>The content of the arp file</figcaption></figure><p>The command returns the content of the file, and as you can see, we get the MAC and IP addresses. To demonstrate the randomization effect, these are the addresses after I restart my phone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VbfSoN_FDLf_7-lpjNYCuA.png" /><figcaption>MAC and IP addresses have changed after restart</figcaption></figure><p>For the same privacy reasons as before, developers don’t get access to this file from the command line. And it’s not possible to read it with the regular File Java API either. Several LLM models were suggesting this, but it crashes the app.</p><pre>FATAL EXCEPTION: DefaultDispatcher-worker-5<br>Process: org.entur.mt.staging, PID: 11491 <br>java.io.FileNotFoundException: /proc/net/arp: open failed: EACCES (Permission denied)</pre><h3>The ping hack</h3><p>Our last resort, one we hoped we would not need, is to use the ping cli command. Since we can find the phone IP address on the Bluetooth tethering interface, we can ping the other addresses in the subnet and see which one responds. There’s only one device connected via tethering, so there should be only one address responding.</p><p>We implemented this in four steps :</p><ol><li>Get all InetAddress objects from NetworkInterface.getNetworkInterfaces() with a name filter bt-pan.</li></ol><pre>fun findBtLanAddresses() = NetworkInterface.getNetworkInterfaces().toList()<br>    .filter { it.name.lowercase() == &quot;bt-pan&quot; }<br>    .flatMap { it.inetAddresses.toList() }</pre><p>2. Keep only IPv4 address and use the cli command ping -c 1 to test each remaining address.</p><pre>fun pingSubMask(addresses: List&lt;InetAddress&gt;): List&lt;InputStream&gt; = addresses<br>    .filterIsInstance&lt;Inet4Address&gt;()<br>    .map { address -&gt;<br>        val parts = address.hostAddress?.split(&quot;.&quot;) ?: return emptyList()<br>        Pair(address.hostAddress, &quot;${parts[0]}.${parts[1]}.${parts[2]}.&quot;)<br>    }<br>    .flatMap { (address, subMask) -&gt;<br>        (254 downTo 1).mapNotNull {<br>            val ip = &quot;$subMask$it&quot;<br>            if (ip == address) {<br>                null<br>            } else {<br>                val pb = ProcessBuilder(&quot;ping&quot;, &quot;-c 1&quot;, ip)<br>                pb.start().inputStream<br>            }<br>        }<br>    }</pre><p>3. Read all the input stream at once and put it in a string.</p><pre>fun readInputStreams(streams: List&lt;InputStream&gt;): String? {<br>    val sequence = SequenceInputStream(Collections.enumeration(streams))<br>    val everything = sequence.bufferedReader().use { it.readText() }<br>    val index = everything.lowercase().indexOf(&quot;1 received&quot;)<br>    return if (index == -1) {<br>        null<br>    } else {<br>        everything.take(index)<br>    }<br>}</pre><pre>...<br><br>PING 10.88.152.218 (10.88.152.218) 56(84) bytes of data.<br>From 10.88.152.72: icmp_seq=1 Destination Host Unreachable<br>--- 10.88.152.218 ping statistics ---<br>1 packets transmitted, 0 received, +1 errors, 100% packet loss, time 0ms<br><br>PING 10.88.152.217 (10.88.152.217) 56(84) bytes of data.<br>64 bytes from 10.88.152.217: icmp_seq=1 ttl=64 time=13.7 ms<br>--- 10.88.152.217 ping statistics ---<br>1 packets transmitted,</pre><p>4. Extract the IP address with the regex \\d+.\\d+.\\d+.\\d+. .</p><pre>fun extractIpAddress(content: String): String = Regex(&quot;(\\d+.\\d+.\\d+.\\d+)&quot;, RegexOption.DOT_MATCHES_ALL)<br>    .findAll(content)<br>    .map { it.groupValues[1] }<br>    .toList()<br>    .last()</pre><p>We stop after the first matching result. It takes between 4 and 5 seconds to get the address, It’s not really fast but it’s still quicker than a user having to navigate around menus on the terminal and scan the QR code.</p><h3>Limitations</h3><p>After a few weeks of testing, our users reported similar feedback :</p><ul><li>The connection between the two devices is still unstable but they can reconnect easily when needed.</li><li>Battery consumption has increased. Not all users reported this, which suggests a more aggressive randomization on some phones. It would lead to more pings and more battery usage.</li><li>We execute the pings in serial, parallelization could probably reduce the execution time from four seconds to one or two.</li></ul><h3>Conclusion</h3><p>It turns out upgrading hardware isn’t always smooth sailing. If you have quite old devices, be ready for troubles. We involved both our hardware provider and the bank terminal manufacturer to fix the issue, but no one had a solution. We even got an email from our provider asking how we’d fixed it because they had another client running into the same problem.</p><p>This ping hack is far from ideal but it works and it is better than manual work. We are still searching for a better alternative when we have some time for it, but no chance so far. Please comment on this post if you ran into the same problem and found a better way to fix it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=680275f129e0" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/reverse-engineering-the-bluetooth-protocol-on-android-680275f129e0">Reverse engineering the Bluetooth protocol on Android</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The code nobody wanted to change]]></title>
            <link>https://medium.com/entur/the-code-nobody-wanted-to-change-df2b6df8b7b4?source=rss-6c34490521e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/df2b6df8b7b4</guid>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[error-management]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Jean Tuffier]]></dc:creator>
            <pubDate>Mon, 02 Mar 2026 10:16:09 GMT</pubDate>
            <atom:updated>2026-03-02T10:16:09.957Z</atom:updated>
            <content:encoded><![CDATA[<h4>and the 1900 reasons we had to</h4><p>Have you ever been in this situation where you arrive at the office just like any other day, seat down at your place, open your computer, but after 5 minutes, you realize it’s gonna be a very long day?</p><p>October 19th 2024, 7:51 am. The automated daily Slack message for failures comes in. The coffee on my desk is still steaming as I brace myself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XvHpHPvOvRjyUmTuECVHeQ.png" /><figcaption>The slack message my team received</figcaption></figure><p>The number just stares right back at me: 1218 failures. My heart sinks, it’s bad, it’s really bad. We usually get 10 errors max per day! I quickly open the detailed report sent by email, hoping it’s a mistake and the day isn’t about to get ruined. But the CSV file confirms it, 1218 lines.</p><h3>Data Detectives</h3><p>I work in the team “onboard” at Entur. We’re in charge of making the apps used by thousands of people working in the public transportation sector. It includes trains, busses and boats all over Norway. The train sector requires offline support, which means we need to accept sales offline and synchronize them with our backend when internet is available again. More details in <a href="https://vimeo.com/1006135689">this presentation</a>.</p><p>The first thing we do is investigate what the problem is, and we quickly notice similar error messages in all the failures. That let us pinpoint where things are going wrong. The 1218 failures occurred because of a problem between one of the Entur’s API and our backend. The data is still safe in our database and we can re-run our synchronization jobs manually. But we also notice other issues recurring at a stable rate and we don’t get any error reports for those. They fly under our radar.</p><p>So I take a short walk to our accountant department and ask them about it. The answer is pretty strait forward: “Yes, you guys have a lot of corrupted sales, we are missing data on many transactions and we have to fix it manually every month. We do have an issue in Jira for that, but it’s never prioritized”. Well, I feel quite embarrassed now since I’m a team lead and I’m not aware of a reported critical error in our software. At that point, I need some solid data to see how bad things are and how much we need to prioritize it.</p><p>It takes us a couple of hours to cover the previous months but we end up with a good overview. We definitely have a problem! We have an average of 800 errors per month between May and September. That includes the train, buss and boat apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W9S1PXKu0X1fPsZO2E44kQ.png" /><figcaption>That’s probably how our accountant have felt for months</figcaption></figure><h3>Where do the errors come from</h3><p>Our app accept payments the following way:</p><ol><li>The employee working in the [train/bus/boat] initiate a sale.</li><li>The traveler presents its bank card to the bank terminal.</li><li>The app receives a confirmation from the bank terminal saying the payment went through.</li><li>The app synchronizes the sale data with Entur APIs.</li></ol><p>That’s when everything goes to plan and the employee has access to internet. The 1218 failures that blow up in our face were due to an API being down.</p><p>But what about the all the other under-the-radar issues? To figure this out, we need to look into our code and investigate the payment module. We are entering a dark realm of “if it ain’t broke, don’t fix it” taken to the extreme. Quick fixes upon quick fixes. We won’t go in the specifics so here’s the tl;dr : the entire payment logic is based on a gigantic procedural block of code. If something goes wrong, the app exits the block, doesn’t roll back anything, sends a few logs and warns the user that something went wrong. We’re good as long as an error happens before a successful payment, but if it fails after, that’s where we get into troubles. The traveler buying a ticket has its money taken but our app fails to register the sale and print the receipt.</p><p>But to be fair with my team, we just came out of another crisis. The integration with the bank terminal was far from stable and it escalated to a really bad place where everything else was down prioritized. Those payment errors feel like the second wave of enemies. We thought we won the war, we just won a battle.</p><h3>The really big fix</h3><p>We have three possibilities in front of us:</p><ol><li>Rewrite everything from scratch : no more legacy code but that would remove a lot of working code. ❌</li><li>Another quick fix : there’s no easy and quick solution around the mess we created. Or it would be signing for another catastrophe in a near future. ❌</li><li>Good ol’ refactoring : ✅</li></ol><p>The plan is to replace that gigantic block of code with many smaller functions abstracted by functional interfaces. It’s difficult because we need to swap pieces one after the other without service interruption. But the logic for selling tickets and giving fines is completely duplicated for some reasons, that would finally be a good time to harmonize it all.</p><h4>1. Delegating to classes</h4><p>To follow the single responsibility principle (SRP), the first step we take is to separate the whole logic in several dedicated classes. We call those dedicated classes “use cases”.</p><p>We basically went from one class doing everything</p><pre>class PaymentExecutor(<br>    // an ocean of dependencies<br>) {<br>    fun pay() {<br>        // about 500 lines of code<br>    }<br><br>    // Dozens of other functions, accumulting to over a 1000 lines.<br>}</pre><p>To many small classes focused on one thing</p><pre>class PaymentExecutor(<br>    private val validator: SaleValidator,<br>    private val processor: BankCardProcessor,<br>    ...<br>) {<br>    fun pay() {<br>        if(validator.checkPaymentParameters()) {<br>            processor.process()<br>        }<br>        ...<br>    }<br>}<br><br>class SaleValidator {<br>    fun checkPaymentParameters(): Boolean {<br>        // some checks here and eventually a throw if something&#39;s wrong.<br>    }<br>}<br><br>class BankCardProcessor {<br>    fun process(): Boolean {<br>        // the logic to make a payment with a bank card<br>    }<br>}</pre><p>Advantages:</p><ul><li>Our code follows the SRP.</li><li>Fewer dependencies in the main class.</li><li>It’s possible to have an understanding of what’s going on.</li><li>It’s possible to maintain.</li></ul><p>Disadvantages:</p><ul><li>The SRP is followed based on good will.</li><li>Each use case can still be too large.</li><li>Nothing prevents apparition of side effects.</li><li>With time, the same problem we had in the original class could come back.</li></ul><h4>2. Delegating to functional interface</h4><p>Since we only have one public function per delegate class, why not use a functional interface instead of a class? And by leveraging operator functions on top of that, we are now looking at functional programming.</p><pre>class PaymentExecutor(<br>    private val validate: SaleValidator,<br>    ...<br>) {<br>    fun pay() {<br>        validate()<br>        ...<br>    }<br>}</pre><pre>fun interface SaleValidator {<br>    suspend operator fun invoke(): Boolean<br>}<br><br>fun SaleValidator() = SaleValidator {<br>    // some checks here and eventually a throw if something&#39;s wrong.<br>}</pre><p>We pair it with Koin to create the instances</p><pre>val paymentModule = module {<br>    factory&lt;SaleValidator&gt; {<br>        SaleValidator()<br>    }<br>    <br>    factory&lt;PaymentExecutor&gt; {<br>        PaymentExecutor(validator = get(), ...)<br>    }<br>}</pre><p>Advantages:</p><ul><li>The SRP is enforced.</li><li>Lower chances to get side effects.</li></ul><p>Disadvantages:</p><ul><li>New concept for some developers.</li><li>When we break the implementation of a use case in several smaller functions rather than one single function, dependencies need to be passed function to function.</li></ul><h4>3. The Arrow library</h4><p>So far so good, but we don’t have any strong error handling. If the logic fails, we throw errors and hope the rest of the code catches them. That’s where the Arrow library comes in with its Either type.</p><pre>class PaymentExecutor(<br>    private val validator: SaleValidator,<br>    ...<br>) {<br>    fun pay() {<br>        either {<br>            validate().bind()<br>            ...<br>        }<br>        ...<br>    }<br>}</pre><pre>fun interface SaleValidator {<br>    suspend operator fun invoke(parameters: PaymentParameters): Either&lt;SaleValidatorError, Unit&gt;<br>}<br><br>fun SaleValidator() = SaleValidator { parameters -&gt;<br>    if (parameters.sum &gt; 0) {<br>        Unit.right()<br>    } else {<br>        SaleValidatorError.InvalidSum(&quot;The sum cannot be inferior to 0&quot;).left()<br>    }<br>}</pre><p>Advantages:</p><ul><li>Strong error handling : we know the code won’t throw errors.</li><li>We also cover errors we didn’t though of before. Returning a Either types forces us to think of many more edge cases.</li></ul><p>Disadvantages:</p><ul><li>A new library and concepts to learn for developers, might not be straight forward for juniors.</li></ul><p>You can find <a href="https://github.com/jeantuffier/Functional-Architecture">here</a> a Github repository with a full example of going from a single regular class to a functional programming paradigm.</p><h3>The results</h3><p>We started the process in November 2024 and it took us about six months to complete the refactoring. Even though we released our code continuously, we weren’t able to get real results before the whole system was in place. By that time we reached the Norwegian summer holidays, which was perfect for testing our solution since the traffic is usually lower. But it meant no real rush-hour stress test neither. So we had to wait for fall 2025 to come, and it was all worth it : no more errors, really 0 failure at all!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hQJrOBp0KnsgK3FkFuAvMg.png" /><figcaption>Our weekly report showing sale failures (in Norwegian)</figcaption></figure><p>While waiting, we created a weekly failure report showing different kind of errors related to sales. The first row shows the percentage of sale failures events out of all the sale events we get. The second shows the same data sorted by transport companies.</p><p>This is a major improvment, in addition of fixing critical issues, we confirm that our new code architecture works perfectly as intended and ensures a 100% reliable sale process.</p><h3>Conclusion</h3><p>With all those changes, we are able to easily build large systems from small, easy to understand and easy to maintain functions. There’s this saying I fall upon that echos quite well our intention:</p><blockquote>The quality of a system is defined by our ability to change it</blockquote><p>I’m not sure who said that first, I saw it multiple times over <a href="https://www.youtube.com/watch?v=vkGb1GR0ge0">youtube</a> and <a href="https://vimeo.com/1115758785">conference presentations,</a> but I think it’s true. We barely knew how the black box worked, nobody wanted to change it and it ended up exploding in our hands. That’s a low quality system if I ever saw one. With the work we did, changes are easy to operate, which mean we can update the system as needed. That possibility is gold in a world where requirements and features change all the time.</p><p>I hope you feel inspired by our year long project that took us from maybe not rock bottom but pretty low, to the summit of bug-free software.</p><p>Thanks for reading our story!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df2b6df8b7b4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/entur/the-code-nobody-wanted-to-change-df2b6df8b7b4">The code nobody wanted to change</a> was originally published in <a href="https://medium.com/entur">Entur</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is this a first nail in the ViewModel’s coffin?]]></title>
            <link>https://medium.com/@JeanTuffier/is-this-a-first-nail-in-the-viewmodels-coffin-1a995b23c52f?source=rss-6c34490521e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a995b23c52f</guid>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Jean Tuffier]]></dc:creator>
            <pubDate>Thu, 03 Jul 2025 08:38:31 GMT</pubDate>
            <atom:updated>2025-07-03T08:38:31.133Z</atom:updated>
            <content:encoded><![CDATA[<p>As written in my <a href="https://medium.com/entur/retaining-states-in-a-pure-composable-way-397706fbc811">previous article</a>, if we ever want to see composable functions used for state management, we need navigation support. What if I tell you Google just released a library that do just that? All onboard the Navigation 3 hype train!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i02bPbAYvh_MH2YGkqlTGQ.png" /><figcaption>Navigation 3 announced at Google I/O 2025</figcaption></figure><h3>The custom solution</h3><p>I began working on the problem shortly after writing my second article. It took me a lot of trials and errors to come up with <a href="https://github.com/jeantuffier/CounterTest/commit/9a78466f0bdcd5c4074c989c9b79caa9d7ab55e8">something usable</a>. I looked at how other components were implemented, like the registry class used to store data from <em>rememberSaveable,</em> and adapted it to work with my own rememberRetained. It required custom logic to store data in memory, custom logic for the navigation backstack, and custom composables to interact with the backstack. Everything’s “custom”. Let’s have a look.</p><p>First I converted the registry to an interface and provided a default implementation.</p><pre>interface RememberRetainedRegistry&lt;KEY, VALUE&gt; {<br>    val values: MutableMap&lt;KEY, VALUE&gt;<br><br>    private fun value(key: KEY): VALUE? =<br>        if (values.keys.any { it == key }) values[key] else null<br><br>    fun clear(key: KEY) {<br>        values.remove(key)<br>        Log.d(&quot;REGISTRY&quot;, &quot;Registry after clear: $values&quot;)<br>    }<br><br>    @Suppress(&quot;UNCHECKED_CAST&quot;)<br>    fun cache(<br>        key: KEY,7<br>        block: @DisallowComposableCalls () -&gt; VALUE,<br>    ): VALUE = value(key) ?: block().also { values[key] = it }<br>        .also { Log.d(&quot;REGISTRY&quot;, &quot;Registry after cache: $values&quot;) }<br><br>    companion object {<br>        private val defaultRegistry: RememberRetainedRegistry&lt;String, Any&gt; by lazy {<br>            GenericRegistry()<br>        }<br><br>        fun &lt;T: Any&gt; cache(<br>            key: String,<br>            block: @DisallowComposableCalls () -&gt; T,<br>        ): T = defaultRegistry.cache(key, block) as T<br>    }<br>}<br><br>class GenericRegistry : RememberRetainedRegistry&lt;String, Any&gt; {<br>    override val values: MutableMap&lt;String, Any&gt; = mutableMapOf()<br>}</pre><p>With this in place, I modified my rememberRetained and produceRetainedState functions to use the default registry or a specified one</p><pre>@Composable<br>fun &lt;T : Any&gt; rememberRetained(<br>    key: String,<br>    calculation: @DisallowComposableCalls () -&gt; T<br>): T = RememberRetainedRegistry.cache(key, calculation)<br><br>@Composable<br>fun &lt;KEY, VALUE&gt; rememberRetained(<br>    key: KEY,<br>    registry: RememberRetainedRegistry&lt;KEY, VALUE&gt;,<br>    calculation: @DisallowComposableCalls () -&gt; VALUE<br>): VALUE = registry.cache(key, calculation)<br><br>@Composable<br>fun &lt;T&gt; produceRetainedState(<br>    key: String,<br>    initialValue: T,<br>    producer: suspend ProduceStateScope&lt;T&gt;.() -&gt; Unit<br>): State&lt;T&gt; {<br>    val result = rememberRetained(key) { mutableStateOf(initialValue) }<br>    LaunchedEffect(Unit) {<br>        ProduceRetainedStateScopeImpl(result, coroutineContext).producer()<br>    }<br>    return result<br>}<br><br>@Composable<br>fun &lt;KEY, VALUE&gt; produceRetainedState(<br>    key: KEY,<br>    initialValue: VALUE,<br>    registry: RememberRetainedRegistry&lt;KEY, MutableState&lt;VALUE&gt;&gt;,<br>    producer: suspend ProduceStateScope&lt;VALUE&gt;.() -&gt; Unit<br>): State&lt;VALUE&gt; {<br>    val result = rememberRetained(key, registry) { mutableStateOf(initialValue) }<br>    LaunchedEffect(Unit) {<br>        ProduceRetainedStateScopeImpl(result, coroutineContext).producer()<br>    }<br>    return result<br>}</pre><p>Now we can define our navigation backstack</p><pre>@Composable<br>fun &lt;KEY, VALUE: Any&gt; rememberNavigationRegistry(): RememberRetainedRegistry&lt;KEY, MutableState&lt;VALUE&gt;&gt; =<br>    rememberRetained(&quot;navigationRegistry&quot;) {<br>        object : RememberRetainedRegistry&lt;KEY, MutableState&lt;VALUE&gt;&gt; {<br>            override val values: MutableMap&lt;KEY, MutableState&lt;VALUE&gt;&gt; = mutableMapOf()<br><br>            override fun toString() = values.map { &quot;key: ${it.key}, value: ${it.value}&quot; }<br>                .joinToString(&quot; | &quot;)<br>        }<br>    }</pre><p>rememberRetained save the “backstack registry” in the default registry. This way, we could potentially have multiple paralleled backstack.</p><p>We just need to update the counterPresenter to specify which registry to use</p><pre>produceRetainedState&lt;ScreenKey, CounterState&gt;(<br>    key = key,<br>    initialValue = CounterState(count = 0),<br>    registry = rememberNavigationRegistry&lt;ScreenKey, CounterState&gt;()<br>)</pre><p>We can see here that the generic parameters are specified to ScreenKey and CounterState. It means the registry will pair a key identifying a screen in the backstack with it’s retained state.</p><p>Finally we need to build the navigation graph. I’ll skip the composable functions and just show how they are used instead.</p><pre>val navigator = rememberNavigator&lt;ScreenKey&gt;()<br>...<br>NavigationBarItem(<br>    ...<br>    onClick = {<br>        selectedItem = index<br>        navigator.navigateTo(screen.key)<br>    }<br>)<br>...<br>Graph(modifier = Modifier.padding(padding), COUNTER_1) {<br>    screen(COUNTER_1) { CounterScreen(COUNTER_1, EventBus()) }<br>    screen(COUNTER_2) { CounterScreen(COUNTER_2, EventBus()) }<br>    screen(COUNTER_3) { CounterScreen(COUNTER_3, EventBus()) }<br>    screen(ScreenKey.NESTED_SCREEN) { NestedScreen() }<br>}</pre><p>rememberNavigator is a helper function for a rememberRetained returning a Navigator. I use it as a simple navigation bus with two events navigateTo and pop. Again, the code source is available <a href="https://github.com/jeantuffier/CounterTest/tree/navigation">here</a>.</p><p>The solution works and I’m satisfied-ish with it but it doesn’t feel very safe. I’m not certain all the elements I came up with are free of unintended side-effects. I would need mentoring from compose runtime experts to check it out and give me their opinion.</p><p>But something interested happened at the same moment I was done with this : the Navigation 3 library was announced, promising a better integration with compose. Maybe I could get rid of my custom UI elements, maybe I could get rid of the custom backstack too! That means I could focus entirely on the “registry” part, great!</p><h3>What’s up with Navigation 3?</h3><p>By now, I assume everyone has heard about the library and what it does. If you haven’t, <a href="https://android-developers.googleblog.com/2025/05/announcing-jetpack-navigation-3-for-compose.html">here’s a good start</a>.</p><p>When comparing my custom solution with Navigation 3, I noticed a key similarity that made the migration process very easy : both are state-oriented. The developer associate a destination with a state. That way, the app can easily retain the different scenes states and remove them when their scope is finished. (Navigation 3 use “scene” rather than “screen”)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oC6XTZW9XBf2OxYwx029MA.png" /><figcaption><a href="https://developer.android.com/guide/navigation/navigation-3/basics">Diagram showing how the back stack changes with user navigation events.</a></figcaption></figure><p>Two composables made ditching all my custom UI code easy: NavDisplay and entryProvider<em>. </em>With this two, we can define all the different scenes of our apps and what should be displayed when navigating to them. But what got me really intrigued was the “<a href="https://developer.android.com/guide/navigation/navigation-3/save-statehttps://developer.android.com/guide/navigation/navigation-3/save-state">Save and manage navigation state</a>” documentation section.</p><blockquote>Ensuring your app’s navigation state persists across various lifecycle events, including configuration changes and process death, is crucial for a good user experience. In Navigation 3, you own your back stack, so there aren’t strict guidelines on how you should create or save it. However, Navigation 3 does offer a convenience method that provides you with a saveable back stack: <a href="https://developer.android.com/reference/kotlin/androidx/navigation3/runtime/package-summary#rememberNavBackStack(kotlin.Array)">rememberNavBackStack</a>.</blockquote><p>NICE! I can also get rid of my custom backstack! I only get to deal with the registry part like I was hoping. But wait a minute, in the “Scoping ViewModels to NavEntrys” subsection, we can read the following.</p><blockquote>You might want to scope a ViewModel to a specific NavEntry on the back stack, rather than the entire Activity. This ensures that the ViewModel&#39;s state is retained only while that particular NavEntry is part of the back stack, and is cleared when the NavEntry is popped.</blockquote><p>Interesting, that’s exactly what I’m trying to do, but with my own produceRetainedState rather than view models. The documentation also says that androidx.lifecycle:lifecycle-viewmodel-navigation3 add-on library provides a NavEntryDecorator that makes it possible. I can check out the implementation and see if I can re-use some of it.</p><p>However I get a first step back there. For some reason, Android studio doesn’t find the dependency. Maybe because I use the alpha3 version and the article was written with the alpha1? Maybe it’s integrated in the dependencies I already have now? Let’s see if I can get anything out of the auto-completion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m2X-9JZyHRO2yg4f6m9VfA.png" /><figcaption>auto-completion result for entryDecorators</figcaption></figure><p>My reaction is pretty much this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MOxLxbltqjFeFVP01PpPEQ.jpeg" /><figcaption>Me realizing Navigation 3 could help much more than what I thought</figcaption></figure><p>This rememberSavedStateNacEntryDecorator<em> </em>looks a lot like rememberSaveable<em>. </em>Let’s see if there’s any documentation for it.</p><blockquote>Returns a SavedStateNavEntryDecorator that is remembered across recompositions.</blockquote><p>Ok, I need to see if I can ditch all my custom stuff and just use a rememberSaveable instead. The only problem is that there’s no produceSaveableState<em>. </em>But I can fix it very easily now, I did it before!</p><pre>@Composable<br>fun &lt;T&gt; produceSaveableState(initialValue: T, producer: suspend ProduceStateScope&lt;T&gt;.() -&gt; Unit): State&lt;T&gt; {<br>    val result = rememberSaveable { mutableStateOf(initialValue) }<br>    LaunchedEffect(Unit) { ProduceStateScopeImpl(result, coroutineContext).producer() }<br>    return result<br>}<br><br>private class ProduceStateScopeImpl&lt;T&gt;(<br>    state: MutableState&lt;T&gt;,<br>    override val coroutineContext: CoroutineContext<br>) : ProduceStateScope&lt;T&gt;, MutableState&lt;T&gt; by state {<br><br>    override suspend fun awaitDispose(onDispose: () -&gt; Unit): Nothing {<br>        try {<br>            suspendCancellableCoroutine&lt;Nothing&gt; {}<br>        } finally {<br>            onDispose()<br>        }<br>    }<br>}</pre><p>And it worked! Navigation 3 handles everything we need out of the box!</p><p>At this point my counter app isn’t interesting enough anymore to illustrate the topic. And I’ve wanted to make an app for my personal library for a while, so it’s now or never.</p><h3>Mighty Bookshelf</h3><p>You can find the complete source code <a href="https://github.com/jeantuffier/Mighty-Bookshelf">here</a>.</p><p>Let’s create two scenes: one for listing books and another for adding new books.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MD_IitVxImFKwUxV-vRViw.jpeg" /><figcaption>The two main screens</figcaption></figure><h3>Listing all the books</h3><p>Let’s start by defining our model</p><pre>@Parcelize<br>data class HomePresenterState(val items: List&lt;Book&gt;) : Parcelable</pre><p>@Parcelize and Parcelable are necessary to use <a href="https://developer.android.com/reference/kotlin/androidx/navigation3/runtime/package-summary#rememberNavBackStack(kotlin.Array)">rememberNavBackStack</a><em> </em>later on. Now let’s define the presenter</p><pre>@Composable<br>fun homeScenePresenter(<br>    selectDao: SelectDao = koinInject(),<br>    dispatcher: CoroutineDispatcher = Dispatchers.IO,<br>): State&lt;HomePresenterState&gt; =<br>    produceSaveableState(HomePresenterState.Empty) {<br>        selectDao.selectAllBooks().onEach { bookWithCreativesList -&gt;<br>            val data = bookWithCreativesList<br>                .groupBy { it.bookId }<br>                .map { it.toBook() }<br>            value = value.copy(items = data)<br>        }.launchIn(this + dispatcher)<br>    }</pre><p>Then we need a NavDisplay</p><pre>val backStack = rememberNavBackStack&lt;Scenes&gt;(Home)<br>CompositionLocalProvider(LocalBackStack provides backStack) {<br>    Scaffold(<br>        floatingActionButton = {<br>            FloatingActionButton(onClick = { backStack.add(Add) }) {<br>                Icon(Icons.Filled.Add, &quot;Add button&quot;)<br>            }<br>        },<br>    ) { padding -&gt;<br>        NavDisplay(<br>            modifier = Modifier.padding(padding),<br>            backStack = backStack,<br>            entryDecorators = listOf(<br>                rememberSavedStateNavEntryDecorator(),<br>            ),<br>            entryProvider = entryProvider {<br>                entry&lt;Home&gt; {<br>                    HomeScene(Modifier.fillMaxSize())<br>                }<br>                entry&lt;Add&gt; {<br>                    AddScene(Modifier.fillMaxSize())<br>                }<br>            }<br>        )<br>    }<br>}</pre><p>I decided to provide the backstack through a local composition so I don’t have to pass it around as a parameter. That way any child of HomeScene and AddScene can modify it with LocalBackStack.current. The floating action button is also responsible for adding the “add scene” to the backstack.</p><p>Finally I just need a grid to show the database content</p><pre>@Composable<br>fun HomeScene(modifier: Modifier) {<br>    val context = LocalContext.current<br>    val state by homeScenePresenter()<br>    LazyVerticalGrid(<br>        modifier = modifier,<br>        columns = GridCells.Adaptive(minSize = 160.dp)<br>    ) {<br>        ...<br>    }<br>}</pre><p>Now we have a scene listing all the books coming from the database. And the data survive configuration changes.</p><h3>Adding a book</h3><p>Same thing, let’s add the model, the presenter and the view.</p><pre>@Parcelize<br>data class AddSceneState(<br>    val type: BookType,<br>    val title: String,<br>    val creatives: List&lt;Creative&gt;,<br>    val reward: String,<br>    val quote: String,<br>    val publisher: String,<br>    val language: String,<br>    val imageUri: String,<br>    val error: String?,<br>) : Parcelable<br><br>@Composable<br>fun addScenePresenter(<br>    events: Flow&lt;AddSceneEvents&gt; = addSceneEventBus().events,<br>    imageAnalysisEventBus: ImageAnalysisEventBus = koinInject(),<br>    addDao: AddDao = koinInject&lt;AddDao&gt;(),<br>    dispatcher: CoroutineDispatcher = Dispatchers.IO,<br>): State&lt;AddSceneState&gt; =<br>    produceSaveableState(AddSceneState.default(BookType.BOOK)) {<br>        events.onEach {<br>            when (it) {<br>                // react to the different events and update<br>                // the state accordingly<br>            }<br>        }.launchIn(this)<br>    }<br><br>@Composable<br>fun AddScene(modifier: Modifier) {<br>    val state by addScenePresenter()<br>    val backstack = LocalBackStack.current<br>    AddSceneContent(<br>        modifier = modifier,<br>        state = state,<br>        navigateToCamera = { backstack.add(Camera) },<br>        ...,<br>    )<br>}</pre><p>We can easily navigate back by calling backstack.pop() from a composable child of AddScene. We can rotate the screen and see that data in every text field is retained. I also added a third scene to take a picture of book covers and extract data automatically with AI. If you navigate to that scene and come back to the “add scene”, the data is also persisted.</p><p>A benefit of composable presenters is their capacity to access Context on their own, through local composition. What’s even nicer is that we can set it as a parameter of the function with a default value, making it easy to test later on. The presenter for the third scene in my app leverage this.</p><pre>@Composable<br>fun cameraPreviewPresenter(<br>    ...<br>    context: Context = LocalContext.current,<br>    lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,<br>    backStack: NavBackStack = LocalBackStack.current,<br>): State&lt;CameraPreviewState&gt; = ...</pre><p>Now I can access strings, contentResolver, etc… in a very easy way. Another thing to notice, and it’s a big one, we don’t need to send “one time navigation events” to our UI! Thanks to navigation 3, we can access our backstack through dependency injection from our presenter/viewModel and modify it from there as needed.</p><h3>Downside</h3><p>There might be one limit to retaining states with Compose and Navigation 3: <a href="https://developer.android.com/develop/ui/compose/state-saving#best_practice">the bundle size</a>.</p><blockquote><em>rememberSaveable</em> uses a <a href="https://developer.android.com/reference/android/os/Bundle"><em>Bundle</em></a> to store UI state, which is shared by other APIs that also write to it, like <a href="https://developer.android.com/reference/android/app/Activity#onSaveInstanceState(android.os.Bundle)"><em>onSaveInstanceState()</em></a> calls in your activity. However, the size of this <em>Bundle</em> is limited, and storing large objects could lead to <a href="https://developer.android.com/reference/android/os/TransactionTooLargeException"><em>TransactionTooLarge</em></a> exceptions in runtime. This can be particularly problematic in single <em>Activity</em> apps where the same <em>Bundle</em> is being used across the app.</blockquote><p>I say “might” because I’m not exactly sure where rememberSavedStateNavEntryDecorator stores data. It needs to be investigated and confirmed.</p><h3>Conclusion</h3><p>In <a href="https://medium.com/entur/compose-for-app-architecture-a2ebeb41ba72">the first article</a> of this series, I used the remember<em> </em>and<em> </em>produceState<em> </em>composable functions. They are the easy/simple side of the spectrum. They can be used right away, no need for anything custom, but they can’t retain a state over configuration changes. Unless you have a screen without anything to retain (like the camera <a href="https://github.com/jeantuffier/Mighty-Bookshelf/blob/main/app/src/main/kotlin/no/northernfield/mightybookshelf/camera/CameraPreviewPresenter.kt">presenter</a> I mentioned earlier for example), it won’t help much.</p><p>On the other side of the spectrum, we have the fully customized solution. It took me a while to come up with a working solutions, and even tough it seems to work fine, it would require much more work to make it to production. It’s the difficult/complicated side of the spectrum.</p><p>Finally, on the middle ground, we have Compose with Navigation 3. The combination of these two sounds very promising and we’ll need to follow up until Navigation 3 gets a stable release. It’s elegant, efficient and works perfectly. And to answer the title of this article : probably not, maybe? But for sure those tools brought me a satisfying solution and I really hope it will flourish into an officially supported concept.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a995b23c52f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retaining screen states with the compose runtime]]></title>
            <link>https://medium.com/entur/retaining-states-in-a-pure-composable-way-397706fbc811?source=rss-6c34490521e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/397706fbc811</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Jean Tuffier]]></dc:creator>
            <pubDate>Fri, 21 Feb 2025 12:27:09 GMT</pubDate>
            <atom:updated>2025-02-21T12:42:10.214Z</atom:updated>
            <content:encoded><![CDATA[<p>A view model is okay, but a composable function will simplify your life.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pqsZNbvP2mt2m-JbI6QB8g.jpeg" /><figcaption>Like Icarus, I was too confident in myself and made a pretty big mistake</figcaption></figure><p>It’s October 24th, I publish my article “Compose for app architecture” and I feel good about it. Even a bit proud since it’s the first I have written. Pretty soon I get some feedback, which fall into two categories:</p><ul><li>How does this programming style hold compared to view models? Especially in regards to configuration changes.</li><li>What about testing?</li></ul><p>Overly confident, I immediately respond to the first category with answers like:</p><blockquote>I did try changing the screen orientation, changing from light to dark theme, putting the app in the background and reopening it. It worked every time, the app did not recreate the state from scratch and kept it’s previous state.</blockquote><blockquote>The data was stored without the use of a view model.</blockquote><blockquote>I did not need to use a <em>rememberSaveble</em>, produceState is build on top of remember and LaunchedEffect. That seems to be enough to survive screen orientation and theme changes.</blockquote><p>Some weeks pass, and I feel a growing doubt concerning my responses. I know that remember and produceState are not supposed to retain data over the recomposition of a function. So why should it work in my project? My curiosity and fear of having written something completely wrong challenges me to take a second look at what I did. After a few hours of investigation looking for a culprit, I ended up finding the cause where I was the least expecting it. So with a dose of humility, I replied in the same thread I so confidently answered in a few weeks before:</p><blockquote>I was completely wrong on this. It worked in my project because I had android:configChanges=&quot;orientation|... in the manifest file.</blockquote><p>I had blocked configuration changes from the manifest file, no wonder the screen state was not lost! While I did not mention anything about surviving recomposition in the first article, I did answer feedback messages saying it was working fine. I was wrong and I want to make it right.</p><p>In this second article, we will have a look at what really happens when using only the functions from the compose-runtime library. Later on, we’ll try to built on it to survive recompositions.</p><h3>Reproducing the error</h3><p>The first article was based on experiments I did in one of my existing projects. It took me a while to figure out what was wrong so I decided to create a proper environment to fix it. A simple counter project is all we need to get started:</p><pre>data class CounterState(val count: Int = 0)<br><br>sealed interface CounterEvent {<br>    object Increment : CounterEvent<br>    object Decrement : CounterEvent<br>    object Reset : CounterEvent<br>}<br><br>@Composable<br>fun counterPresenter(events: Flow&lt;CounterEvent&gt;): State&lt;CounterState&gt; =<br>    produceState(CounterState()) {<br>        events.onEach {<br>            value = when (it) {<br>                Increment -&gt; value.copy(count = value.count + 1)<br>                Decrement -&gt; value.copy(count = value.count - 1)<br>                Reset -&gt; CounterState()<br>            }<br>        }.launchIn(this)<br>    }<br><br>@Composable<br>fun CounterScreen(bus: CounterEventBus) {<br>    val state by counterPresenter(events = bus.events)<br>    Log.d(&quot;CounterScreen&quot;, &quot;CounterScreen recomposed with counter value to: ${state.count}&quot;)<br>    ...<br>}</pre><p>You can find the full implementation here: <a href="https://github.com/jeantuffier/CounterTest/tree/the-issue">https://github.com/jeantuffier/CounterTest/tree/the-issue</a>.</p><p>By running this, we can clearly see the error when rotating the device’s screen</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*wz_qWDgcVk_vfL8Vh4zAfQ.png" /></figure><p>The state goes back to 0 at every screen rotation. Proving produceState does not retain states over recomposition. Now we are ready to figure out how we to fix the issue.</p><h3>Remembering the state</h3><p>I talked about Circuit in my first article, saying that they have a fully fledged framework for handling entire apps with compose. Turns out, they have already fixed that retaining issue. <a href="https://chrisbanes.me/posts/retaining-beyond-viewmodels/">https://chrisbanes.me/posts/retaining-beyond-viewmodels</a>. The rememberRetained function holds the state in memory so the composable function can access it after a recomposition happens.</p><p>With that said, let’s create our own in-memory registry:</p><pre>object RememberRetainedRegistry {<br>    private val values = mutableMapOf&lt;String, Any&gt;()<br><br>    private fun value(key: String): Any? =<br>        if (values.keys.any { it == key }) values[key] else null<br><br>    @Suppress(&quot;UNCHECKED_CAST&quot;)<br>    fun &lt;T : Any&gt; cache(<br>        key: String,<br>        block: @DisallowComposableCalls () -&gt; T,<br>    ): T = value(key)?.let { it as T } ?: block().also { values[key] = it }<br>}</pre><p>The states are retained inside a MutableMap&lt;String, Any&gt; with String being the key identifying a state in the registry and Any the state object to retain. The trick here is to use a mutableStateOf from Compose to be able to update the state value associated with a given key. To access those values, one must use the cache function that will register a new state for a new key or return the existing value.</p><p>By looking at how remember, rememberSaveble and produceStateare implemented in the compose library, we can also create our own “retained” versions.</p><pre>@Composable<br>fun &lt;T : Any&gt; rememberRetained(<br>    key: String,<br>    calculation: @DisallowComposableCalls () -&gt; T<br>): T = RememberRetainedRegistry.cache(key, calculation)<br><br>@Composable<br>fun &lt;T&gt; produceRetainedState(<br>    key: String,<br>    initialValue: T,<br>    producer: suspend ProduceStateScope&lt;T&gt;.() -&gt; Unit<br>): State&lt;T&gt; {<br>    val result = rememberRetained(key) { mutableStateOf(initialValue) }<br>    LaunchedEffect(Unit) {<br>        ProduceRetainedStateScopeImpl(result, coroutineContext).producer()<br>    }<br>    return result<br>}<br><br>class ProduceRetainedStateScopeImpl&lt;T&gt;(<br>    state: MutableState&lt;T&gt;,<br>    override val coroutineContext: CoroutineContext<br>) : ProduceStateScope&lt;T&gt;, MutableState&lt;T&gt; by state {<br><br>    override suspend fun awaitDispose(onDispose: () -&gt; Unit): Nothing {<br>        try {<br>            suspendCancellableCoroutine&lt;Nothing&gt; { }<br>        } finally {<br>            onDispose()<br>        }<br>    }<br>}</pre><p>rememberRetained is equivalent to a regular remember with the capacity of surviving recompositions. produceRetainedState is exactly the same as produceState, the only difference is that it uses rememberRetained. Finally, ProduceRetainedStateScopeImpl is a copy of ProduceStateScopeImpl because it’s not public.</p><p>Now we can implement a presenter function with a state that will survive recompositions!</p><pre>@Composable<br>fun counterPresenter(key: String, events: Flow&lt;CounterEvent&gt;): State&lt;CounterState&gt; =<br>    produceRetainedState(key = key, initialValue = CounterState(count = 0)) {<br>        events.onEach { event -&gt;<br>            value = when (event) {<br>                Increment -&gt; value.copy(count = value.count + 1)<br>                Decrement -&gt; value.copy(count = value.count - 1)<br>                Reset -&gt; value.copy(count = 0)<br>            }<br>        }.launchIn(this)<br>    }<br><br>@Composable<br>fun CounterScreen(bus: CounterEventBus) {<br>    val state by counterPresenter(&quot;counter&quot;, bus.events)<br>    CounterScreenContent(<br>        count = state.count,<br>        onDecrement = { bus.produceEvent(Decrement) },<br>        onReset = { bus.produceEvent(Reset) },<br>        onIncrement = { bus.produceEvent(Increment) },<br>    )<br>}</pre><p>counterPresenter takes a key parameter and uses produceRetainedState. The name of the screen can be used as a key for example, as shown in CounterScreen.</p><p>You can find the complete implementation here: <a href="https://github.com/jeantuffier/CounterTest">https://github.com/jeantuffier/CounterTest</a> (on the main branch)</p><p>When we run the app, orientation changes do not affect the counter value anymore after the screen recreation!</p><h3>How do we test this?</h3><p>We can start by ensuring that the presenter updates the value correctly:</p><pre>@Test<br>fun testCounterPresenter() {<br>    val bus = CounterEventBus()<br>    composeTestRule.activity.setContent {<br>        val state = counterPresenter(&quot;counter&quot;, bus.events)<br>        assertEquals(0, state.value.count)<br><br>        bus.produceEvent(Increment)<br>        bus.produceEvent(Increment)<br>        assertEquals(2, state.value.count)<br><br>        bus.produceEvent(Reset)<br>        assertEquals(0, state.value.count)<br><br>        bus.produceEvent(Decrement)<br>        assertEquals(-1, state.value.count)<br>    }<br>}</pre><p>Then we can check in the UI that the text is displayed properly and survives an orientation change:</p><pre>@Test<br>fun testRetainedState() {<br>    composeTestRule.activity.setContent {<br>        CounterTestTheme {<br>            CounterScreen(CounterEventBus())<br>        }<br>    }<br><br>    composeTestRule.onNodeWithTag(&quot;counter&quot;).assertTextContains(&quot;Counter: 0&quot;)<br>    composeTestRule.onNodeWithTag(&quot;increment&quot;).performClick()<br>    composeTestRule.onNodeWithTag(&quot;counter&quot;).assertTextContains(&quot;Counter: 1&quot;)<br>    composeTestRule.onNodeWithTag(&quot;increment&quot;).performClick()<br>    composeTestRule.onNodeWithTag(&quot;counter&quot;).assertTextContains(&quot;Counter: 2&quot;)<br>    composeTestRule.onNodeWithTag(&quot;decrement&quot;).performClick()<br>    composeTestRule.onNodeWithTag(&quot;counter&quot;).assertTextContains(&quot;Counter: 1&quot;)<br>    composeTestRule.onNodeWithTag(&quot;reset&quot;).performClick()<br>    composeTestRule.onNodeWithTag(&quot;counter&quot;).assertTextContains(&quot;Counter: 0&quot;)<br><br>    composeTestRule.onNodeWithTag(&quot;increment&quot;).performClick()<br>    composeTestRule.onNodeWithTag(&quot;increment&quot;).performClick()<br>    composeTestRule.onNodeWithTag(&quot;increment&quot;).performClick()<br>    composeTestRule.onNodeWithTag(&quot;counter&quot;).assertTextContains(&quot;Counter: 3&quot;)<br><br>    composeTestRule.waitForIdle()<br>    composeTestRule.activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE<br>    composeTestRule.waitForIdle()<br><br>    composeTestRule.onNodeWithTag(&quot;counter&quot;).assertTextContains(&quot;Counter: 3&quot;)<br>}</pre><p>It’s pretty simple and straightforward. The test programmatically clicks on the increment, decrement, reset buttons and checks that the text is updated accordingly. Full implementation here: <a href="https://github.com/jeantuffier/CounterTest/blob/main/app/src/androidTest/java/no/northernfield/countertest/CounterPresenterTest.kt">https://github.com/jeantuffier/CounterTest/blob/main/app/src/androidTest/java/no/northernfield/countertest/CounterPresenterTest.kt</a></p><h3>Conclusion</h3><p>We now have a working presenter surviving configuration changes. The state remains the same after a screen orientation or a theme change. We are able to test the presenter independently from the UI first, and then the UI itself with value updates and configuration changes.</p><p>But there’s a bigger problem that I haven’t mentioned yet: once the state is in the registry, it’s there until the app is killed. I haven’t implemented any clearing mechanism that would remove the state once it’s not needed anymore. While it isn’t a problem for the counter project, any “real” app requires it. And this brings us to the navigation topic; the registry should retain any state associated with a presenter on the navigation back stack. As soon as a composable is removed from it, the registry should drop the state. It is also the logic adopted by Circuit.</p><blockquote>When using Circuit’s <a href="https://slackhq.github.io/circuit/navigation/">Navigation</a> system, any retained state created by presenters will be retained, <strong>for as long as those screens are on the back stack</strong>. This is consistent with how ViewModels are stored with AndroidX Navigation, so hopefully it’s not too foreign to developers.</blockquote><p>A third article will be published when I have a solution for this problem, in the meantime feel free to write to me/hit me up on the Kotlin Slack, LinkedIn or leave a comment here. I’m looking forward to reading your feedback again!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=397706fbc811" width="1" height="1" alt=""><hr><p><a href="https://medium.com/entur/retaining-states-in-a-pure-composable-way-397706fbc811">Retaining screen states with the compose runtime</a> was originally published in <a href="https://medium.com/entur">Entur</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Compose for app architecture]]></title>
            <link>https://medium.com/entur/compose-for-app-architecture-a2ebeb41ba72?source=rss-6c34490521e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2ebeb41ba72</guid>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[developement]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Jean Tuffier]]></dc:creator>
            <pubDate>Thu, 24 Oct 2024 12:48:42 GMT</pubDate>
            <atom:updated>2024-12-21T21:23:29.126Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bd6xmJOJ1uPXRB_RPKvG1Q.jpeg" /><figcaption>an illustration of state management in mobile application development</figcaption></figure><p>Android development has changed a lot since 2013, from MVC pattern to MVI in the last few years. With the introduction of Compose, we have the possibility to use newer and powerful tools to improve our architectures. This article will explore how we can elevate our code and create even more maintainable projects.</p><h3>The theory</h3><p>From everything inside an activity to modern design patterns, architectures in the android world have renewed themselves several times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HsxRCqIkKog29L3VYnSbbQ.jpeg" /><figcaption>evolution of architecture patterns used in android development</figcaption></figure><p>MVC introduced the separation of concern between the UI, the business logic, and the data. MVP added abstractions between the layers. With the gain in popularity of reactive-programming and Rx-Java came MVVM, which changed quite a lot the way programmers conceptualize the data flow across an app (UDF). When Coroutines and Flows joined the party, MVI took off by leveraging several of their advantages.</p><p>Today, Compose gives us a significant paradigm change and several developers imagine different new ways to further improve our code bases. Even though Compose is often assimilated to UI, some of its component like the runtime library focuses purely on data structures and logic. As stated by the <a href="https://github.com/slackhq/circuit">Circuit</a> documentation :</p><blockquote><em>Compose itself is essentially two libraries — Compose Compiler and Compose UI. Most folks usually think of Compose UI, but the compiler (and associated runtime) are actually not specific to UI at all and offer powerful state management APIs.</em></blockquote><blockquote><em>Jake Wharton has an excellent post about this: </em><a href="https://jakewharton.com/a-jetpack-compose-by-any-other-name/"><em>A Jetpack Compose by any other name — Jake Wharton</em></a></blockquote><p>Two projects have recently taken the spotlight in the area of app architecture with Compose :</p><ul><li><a href="https://github.com/cashapp/molecule">Molecule</a> from Cashapp, builds Flow/Stateflow with Compose but requires a CoroutineScope from the outside. One needs to either create it or get the scope from a component with a lifecycle (activity, fragment and view model) or a side effect like <a href="https://developer.android.com/develop/ui/compose/side-effects#remembercoroutinescope">rememberCoroutineScope</a> from a composable function.</li><li><a href="https://github.com/slackhq/circuit">Circuit</a> from Slack is a framework built 100% on top of Compose, it deals with logic and UI. From the documentation :</li></ul><blockquote><em>Circuit is a simple, lightweight, and extensible framework for building Kotlin applications that’s Compose from the ground up. It builds upon core principles we already know like Presenters and UDF, and adds native support in its framework for all the other requirements we set out for above.</em></blockquote><p>Circuit resembles a lot to another project called “The Composable Architecture” (TCA) from Point Free, a framework for Swift development. While Circuit documentation mentions UDF and Presenter patterns, they do not use a specific name for the general architecture of the framework. One can say it is an adapted implementation of TCA leveraging Kotlin and Compose.</p><p>The projects are designed for different OS and programming languages but implement the same concepts. Three main components are necessary to build a feature :</p><ul><li>State: A structure that describes which data is needed to execute the logic and render the UI.</li><li>Action: A Structure representing all the events that can happen on a screen, due to user inputs, like a click on a button for example.</li><li>Presenter (Reducer in TCA): A function describing how the current state evolves based on a specific action.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZF87ytKCPsqbUShUZYGfpA.jpeg" /><figcaption>Screens emit actions that are converted into state update by the presenter</figcaption></figure><p>One downside of Circuit is that it comes with a complete solution for both logic and UI. One cannot integrate it in existing code, it needs to be refactored completely. But with a minimum of boilerplate, we can implement our own TCA pattern in any existing app.</p><h3>Show me the code</h3><p>Let’s create a minimal feature showing departure times at a given train station. We’ll focus on the essentials and focus on some parts for the sake of this demonstration. We can start by creating the state structure :</p><pre>data class DepartureState(<br>    val isLoading: Boolean,<br>    val stationId: Int,<br>    val departures: List&lt;String&gt;,<br>)</pre><ul><li>isLoading indicates when the UI should show a spinner or something similar to represent a loading/waiting time.</li><li>stationId is the ID of the chosen train station.</li><li>departures represents all the departure times for a station.</li></ul><p>Then we can define the actions available in our screen :</p><pre>sealed interface DeparturesDemoScreenAction {<br>    data class OnLoadMoreClicked(val stationId: Int): DeparturesDemoScreenAction<br>}</pre><p>We use a sealed interface to limit possibilities and reinforce our logic. We define an OnLoadMoreClicked action that will be used when the user clicks on a “Load more” button. Now we need a presenter to transform OnLoadMoreClicked into a new (or updated) DepartureState.</p><pre>fun interface GetDeparturesService {<br>    suspend operator fun invoke(station: Int, offset: Int, limit: Int): List&lt;String&gt;<br>} <br><br>fun interface DeparturesPresenter {<br>    @Composable     <br>    operator fun invoke(actions: Flow&lt;DeparturesDemoScreenAction&gt;): State&lt;DepartureState&gt; <br>} <br><br>@Composable fun departuresPresenter(getDeparturesService: GetDeparturesService) = DeparturesPresenter { actions -&gt;<br>    val initialValue = DepartureState(isLoading = false, stationId = 0, departures = emptyList())<br>    produceState(initialValue) {<br>        launch {<br>            actions.collect {<br>                when(it) {                     <br>                    is DeparturesDemoScreenAction.OnLoadMoreClicked -&gt; {<br>                        value = value.copy(isLoading = true)<br>                        val offset = if (it.stationId == value.stationId) value.departures.size else 0<br>                        val departures = getDeparturesService(it.stationId, offset, 10)<br>                        value = value.copy(isLoading = false, departures = value.departures + departures)<br>                    }<br>                }<br>            }<br>        }     <br>    }<br>}</pre><p>First, we give an initial value to our state. We then use a produceState from the Compose framework to create a block of code capable of emitting a Compose State object. If the IDs match, we append content to the list otherwise we replace it.</p><p>Now we only need a @Composable function to show the UI and use what we have created so far.</p><pre>@Composable fun DeparturesScreen(presenter: DeparturesPresenter) {<br>    val eventBus = EventBus&lt;DeparturesDemoScreenAction&gt;()<br>    val state by presenter(eventBus.events)     <br><br>    if (state.isLoading) {<br>        CircularProgressIndicator()<br>    }<br><br>    var selectedStation by remember { mutableIntStateOf(1) }<br>    Column {<br>        Row {<br>            (1..3).forEach {<br>            Button(<br>                onClick = { <br>                    selectedStation = it<br>                    eventBus.produceEvent(DeparturesDemoScreenAction.OnLoadMoreClicked(selectedStation))<br>                }<br>            ) { Text(&quot;Station $it&quot;) }<br>        } <br>            <br>        state.departures.forEach {<br>            Text(it)<br>        }<br><br>        if (state.departures.isNotEmpty()) {<br>            Button(<br>                onClick = { eventBus.produceEvent(DeparturesDemoScreenAction.OnLoadMoreClicked(selectedStation)) }<br>            ) { Text(&quot;Load more&quot;) }<br>        }<br>    }<br>}</pre><p>Finally, we show three buttons that can be used to choose a train station, a list containing the departures, and a button to load more data if the list is not empty.</p><h3>Great… but why?</h3><p>ViewModel was originally designed for activities and fragments. The documentation on the class itself states :</p><blockquote><em>ViewModel is a class that is responsible for preparing and managing the data for an Activity or a Fragment.</em></blockquote><p>To get an instance of a view model, a whole bunch of androidx.lifecycle classes are used under the hood, like ViewModelProvider, ViewModelStoreOwner, HolderFragment etc… For composable functions, there is a viewModel function inside android.lifecycle.viewmodel.compose that can be used to get the instance of a view model. But the view model will be scoped to the activity or fragment “owning” the composable function, not the function where it is actually used itself.</p><blockquote>Returns an existing ViewModel or creates a new one in the given owner (usually, a fragment or an activity), defaulting to the owner provided by LocalViewModelStoreOwner.<br>The created ViewModel is associated with the given viewModelStoreOwner and will be retained as long as the owner is alive (e. g. if it is an activity, until it is finished or process is killed).</blockquote><p>It’s possible to avoid the issue by using additional libraries like Dagger/Hilt or Koin but it means additional “backstage” work. A presenter emitting states with produceState is automatically scoped to the composable function calling it.</p><blockquote>The producer is launched when produceState enters the Composition, and will be cancelled when it leaves the Composition. The returned State conflates; setting the same value won&#39;t trigger a recomposition.</blockquote><p>For those interested in how fragments internally work, here’s some detailed reading: <a href="https://medium.com/android-news/dive-deep-into-androids-viewmodel-android-architecture-components-e0a7ded26f70">Dive deep into Android’s ViewModel — Android Architecture Components</a>.</p><p>We can also mention that the pattern used with view model consisting of a combination of a private MutableStateFlow and a public StateFlow isn’t necessary anymore since the produceState function takes care of it for us.</p><p>If we widen our scope from android only to kotlin multiplatform, we can find a strong advantage in the TCA pattern. It provides friendly APIs to the swift developer most likely already familiar with it’s concepts while view models are not a thing in the swift/ios world. (A library like <a href="https://github.com/rickclephas/KMP-NativeCoroutines">KMP-NativeCoroutines</a> will help simplify interfacing shared logic).</p><p>By leveraging the functional programming approach provided by TCA, we strengthen our codebase and future proof it against all sort of potential creeping issues that come up on long living projects.</p><h3>Edit 21/12/2024</h3><p>I did share this post on the Kotlin Slack community after posting it and got a few comments back. Mostly regarding the limitations of produceState in Android for retaining a state over activity recreation and configuration changes in general. My project didn’t have any issue with this so i replied that I tested several cases and it “all worked fine, no problem here”. But that was <em>very </em>wrong. I totally forgot I used android:configChanges=&quot;orientation|...&quot; in the manifest file. To learn out of my mistake and share whatever discoveries I’ll make, I created a counter project to test any solutions to this issue : <a href="https://github.com/jeantuffier/CounterTest">https://github.com/jeantuffier/CounterTest</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2ebeb41ba72" width="1" height="1" alt=""><hr><p><a href="https://medium.com/entur/compose-for-app-architecture-a2ebeb41ba72">Compose for app architecture</a> was originally published in <a href="https://medium.com/entur">Entur</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>