<?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 David Santos on Medium]]></title>
        <description><![CDATA[Stories by David Santos on Medium]]></description>
        <link>https://medium.com/@dsantosp?source=rss-6928ac19c493------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*5oNbNRxQl2V7-Yfg</url>
            <title>Stories by David Santos on Medium</title>
            <link>https://medium.com/@dsantosp?source=rss-6928ac19c493------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 05:53:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dsantosp/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[First time experience at DroidKaigi 2025]]></title>
            <link>https://medium.com/eureka-engineering/first-time-experience-at-droidkaigi-2025-89f7cb1a357a?source=rss-6928ac19c493------2</link>
            <guid isPermaLink="false">https://medium.com/p/89f7cb1a357a</guid>
            <category><![CDATA[droidkaigi]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[David Santos]]></dc:creator>
            <pubDate>Fri, 19 Sep 2025 04:03:50 GMT</pubDate>
            <atom:updated>2025-09-19T04:03:50.880Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7XMVZIJFzoAZmq2EpRz7Aw.jpeg" /></figure><p>Assisting for the first time to an Android conference</p><h3>Introduction</h3><p>I want to start by saying that this was my first time attending an Android conference in person. I had always followed them online, watching the recorded sessions. So, for this article, I would like to focus more on my personal experience and impressions, rather than diving deep into the technical details.</p><p>I would like to highlight the variety of events available over the two days. These activities made the conference feel more dynamic and fun, offering plenty of opportunities to interact with others. Some of these included stamp collecting, a nail art session, a Japanese festival (Matsuri), an after-party featuring a マグロ解体ショー (tuna carving show), and various themed chat spots for mingling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q2JDQ39W4LoSQwQjb1hplA.jpeg" /><figcaption>nail art session</figcaption></figure><p>Listing and briefly explaining every presentation I attended would make this article too long. Instead, I’ve decided to pick up the ones I found most interesting, offering my impressions and highlighting any technical aspects that could be applied to our work at Eureka.</p><h3>09/11</h3><h4><a href="https://www.youtube.com/watch?v=pNyNUnLfNzA">Learning Large-Screen Support from the Ground Up — Development Insights from a “Large screen differentiated”-Certified App-</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1JrfTxHg04ZxL5dPWoqygg.jpeg" /></figure><p>As seen in the recent behavior change for apps targeting Android 16 or higher, displays with a width of 600dp or more will ignore orientation, resizability, and aspect ratio restrictions. This clearly shows Google is pushing developers to support large screens, turning what was once a ‘nice-to-have’ into a ‘must-have’ feature.</p><blockquote>With Android apps now running on a variety of devices (such as phones, tablets, foldables, desktops, cars, and TVs) and windowing modes on large screens (such as split screen and desktop windowing), developers should build Android apps that adapt to any screen and window size, regardless of device orientation. Paradigms like restricting orientation and resizability are too restrictive in today’s multidevice world.</blockquote><blockquote><a href="https://developer.android.com/about/versions/16/behavior-changes-16#adaptive-layouts">https://developer.android.com/about/versions/16/behavior-changes-16#adaptive-layouts</a></blockquote><p>It’s important to note that Google doesn’t require a premium large-screen experience from the start. Instead, they offer <a href="https://developer.android.com/docs/quality-guidelines/large-screen-app-quality">three tiers of support</a> allowing us to choose the level that best fits our use cases, development schedule, and business goals:</p><ul><li>Tier 3 (basic) — large screen ready</li></ul><blockquote>Users can complete critical task flows but with a less than optimal user experience. Your app runs full screen (or full window in multi-window mode), but app layout might not be ideal. The app is not letterboxed; it does not run in compatibility mode. The app provides basic support for external input devices, including keyboard, mouse, trackpad, and stylus.</blockquote><ul><li>Tier 2 (better) — large screen optimized</li></ul><blockquote>Your app implements layout optimizations for all screen sizes and device configurations along with enhanced support for external input devices.</blockquote><ul><li>Tier 1 (best) — large screen differentiated</li></ul><blockquote>Your app provides a user experience designed for tablets, foldables, and ChromeOS devices. Where applicable, the app supports multitasking, foldable postures, drag and drop, and stylus input.</blockquote><p>The presentation also mentioned that reaching Tier 2 or 1 means the app is nearly ready for Android XR, qualifying as an “Android XR compatible large screen app”.</p><p>The speaker recommended that if an app is still primarily View-based, or only partially uses Compose, migrating fully to Compose is the best path forward. This is because Compose simplifies the logic for adapting layouts based on screen and window size. Jetpack Compose Navigation 3 also facilitates the implementation of large-screen layouts.</p><p>Below is the recommended phased approach by the speaker:</p><p><strong>Step 1:</strong> TIER 3 support — possible with View base</p><ul><li>run app in full screen</li><li>handle configuration changes properly</li><li>add scroll support and max width constraints</li></ul><p><strong>Step 2:</strong> optimize for large screens targeting TIER 2+</p><ul><li>flexible layout support</li><li>keyboard and mouse support</li></ul><p>At Eureka, we haven’t officially committed to first experience large-screen support, though we’ve always aimed to provide an experience close to what would be considered Tier 1. I believe now is an excellent time to discuss our current strategy with the Android team and, if necessary, rethink our direction for the near future.</p><h4><a href="https://www.youtube.com/watch?v=c-OO-8diTpk">Beyond Exceptions: Building Resilient Android Apps with Safety-Critical Principles</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FVM4TMOYcQ7I7g4p4SE85g.jpeg" /></figure><p>The session’s main argument is to avoid using exceptions to represent errors in domain logic. Relying on exceptions for this purpose is problematic because it requires developers to understand the internal implementation details to handle all possible cases exhaustively.</p><p>The presentation also critiqued the use of Kotlin’s built-in Result type, pointing out several drawbacks:</p><ul><li>It leads to the unnecessary creation of exception classes.</li><li>It does not allow for exhaustive, compile-time checking of all possible error outcomes.</li><li>The Result.runCatching function inadvertently catches CancellationException, which can interfere with the intended behavior of Kotlin Coroutines.</li></ul><p>It was noted that even the official Kotlin team advises against using the Result type for handling domain-specific errors, as stated in their <a href="https://github.com/Kotlin/KEEP/blob/main/proposals/stdlib/KEEP-0127-result.md#error-handling-style-and-exceptions">KEEP proposal</a>.</p><p>For more appropriate error representation, the speaker recommended two primary approaches:</p><ul><li>Using null for simple, lightweight error cases.</li><li>Defining custom classes with a sealed interface for more detailed and robust error modeling.</li></ul><p>Looking to the future, the talk mentioned a potential new language feature called “<a href="https://www.youtube.com/watch?v=IUrA3mDSWZQ">Rich Errors</a>” planned for Kotlin 2.4.</p><p>As a personal experience, I have been struggling with this topic in our application for some time. Recently, I have been digging into this and came up with a similar conclusion about avoiding exceptions and instead defining custom classes with a sealed interface for errors representing domain logic. However, as mentioned in the presentation, you need to write some extra code, so I am quite happy that the <strong>Rich Errors</strong> feature will be released.</p><h4>After Party</h4><p>After the day’s presentations, there was an after-party featuring a “Maguro Kaitai Show” (a live tuna carving demonstration). The room was set up with standing tables for 7–8 people, creating a dynamic and casual atmosphere for eating, drinking, and talking. <br>Since it was my first time at the conference and I didn’t know anyone, it was a bit challenging to join a group at first. However, I eventually introduced myself to a table of strangers and started socializing. <br>Overall, it was a great experience where I got to meet different people and share our experiences as Android engineers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EjSUCJ0FyXN9slnkJ8JpTw.jpeg" /><figcaption>Maguro Kaitai Show</figcaption></figure><h3>09/12</h3><h4><a href="https://www.youtube.com/watch?v=wIR-zMqJdKk">The Complete Guide to Android Value Passing: Control Your Architecture, Control Your “Passing”!</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qTwGBrQN3WakFw-r_k9aUQ.jpeg" /></figure><p>I will not go into detail about the content of this session, but I wanted to mention it because it was one of the best I attended during the conference. The clarity of the explanations, the use of examples, the presentation flow, and the overall dynamic were outstanding. I recommend watching this presentation not just for its technical content, but also as a great example of how to deliver an effective talk.</p><h4><a href="http://youtube.com/watch?v=bcmK90SRN-0">Cache Me If You Can</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vwgtUyJ5yt6CWo049qccSw.jpeg" /></figure><p>This presentation is great for anyone like me who wants to dig deeper into Gradle and understand how it works behind the scenes.</p><p>It provides a grasp of the Gradle and AGP lifecycles, explaining what happens in each phase and how to use their APIs and extensions. It also explains the typical bottlenecks in each phase and offers API usage strategies that respect the lifecycle.</p><p>Furthermore, the presentation gives us mechanisms and best practices to speed up builds with different kinds of caching systems, like the Gradle Build Cache and Configuration Cache. It also presents common anti-patterns that disable these caches and how to avoid them.</p><p>I think the timing was perfect for me to attend this presentation, since I am currently working on our application’s Gradle configuration and also trying to enable the configuration cache. Its contents will be very helpful for my current work.</p><h4>Themed Meetups</h4><p>During lunch on the second day, I joined a themed meetup called <strong>Parenting and Work</strong>. <br>It was a very enriching experience, hearing firsthand how families with children balance their careers with parenting. Most attendees worked fully remotely or relied on grandparents for help during work hours. <br>We also discussed topics like the pros and cons of different housing types, such as apartments (mansion) versus detached houses.</p><h3>Final Impressions</h3><p>Attending my first in-person Android conference was a completely different experience from watching recorded sessions online. The biggest takeaway for me wasn’t just the technical knowledge, but the strong sense of community. The themed meetups, casual conversations at the after-party, and the dynamic social events created an environment where it was easy to connect with other developers, share challenges, and learn from their experiences. This personal interaction is something you simply can’t get from a recorded video. <br>I’m returning to work not only with new technical insights to discuss with the team at Eureka but also with a renewed sense of motivation and a broader perspective on the global Android community. <br>It was a valuable experience that I would highly recommend.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89f7cb1a357a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/eureka-engineering/first-time-experience-at-droidkaigi-2025-89f7cb1a357a">First time experience at DroidKaigi 2025</a> was originally published in <a href="https://medium.com/eureka-engineering">Pairs Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving Android release process at Eureka (Pairs app)]]></title>
            <link>https://medium.com/eureka-engineering/improving-android-release-process-at-eureka-pairs-app-1f93002f4c95?source=rss-6928ac19c493------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f93002f4c95</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[release-process]]></category>
            <dc:creator><![CDATA[David Santos]]></dc:creator>
            <pubDate>Mon, 16 Dec 2024 00:32:19 GMT</pubDate>
            <atom:updated>2024-12-16T00:32:19.151Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-zRFT38imfMw_kG4MUgpwg.jpeg" /></figure><h4><strong>Evolving from a manual local process to a remote, automated workflow</strong></h4><p><em>This is the December 16th article for Pairs Engineering Advent Calendar 2024.</em></p><h3>Introduction</h3><p>With many technologies and systems now available to automate release processes, we can save valuable time, reduce manual effort, and minimize the risk of human error. It’s time to rethink the Android release process we’ve been using at Eureka for many years and make the leap towards a more automated, efficient system.</p><h3>Purpose of this article</h3><p>The goal of this article is to present our current Android release process at Eureka and explore ways we can evolve it to require minimal human interaction and become remotely actionable. While nothing has been implemented yet, this article could serve as a technical draft for the future.</p><h3>Release process</h3><p>Currently, we conduct weekly releases, even if there are no new product features. The primary aim is to keep the app up-to-date with the latest code, distributing minor fixes and improvements as soon as possible. We have divided the overall release into the following phases.</p><h4>One day before pre-submission testing</h4><p>This phase essentially marks code freeze day, where we prepare the app version for testing by the Android and QA teams.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dn0JKxz0v-7vs-2r5whEog.png" /></figure><ul><li>code freeze: Aside from a calendar event, we don’t have a formal reminder. We could introduce a Slack bot to announce code freeze in the morning, allowing team members time to merge their PRs if necessary.</li><li>check if the previous version has been merged into develop: This is currently a manual task. We could use GitHub Actions to perform this check at a specific day and time using a <a href="https://docs.github.com/en/actions/writing-workflows/choosing-when-your-workflow-runs/events-that-trigger-workflows#schedule">schedule</a> trigger. <br>This could be a workflow together with the code freeze slack announcement.</li><li>deploy minified debug version app: This step involves multiple subtasks, many of which are managed through a local script. These subtasks could be migrated to a GitHub Actions workflow triggered by <a href="https://docs.github.com/en/actions/writing-workflows/choosing-when-your-workflow-runs/events-that-trigger-workflows#workflow_dispatch">workflow_dispatch</a>.<br>For the <em>create PR against master branch</em> task we could use either a <a href="https://github.com/marketplace/actions/create-pull-request">third party action</a> or use <a href="https://cli.github.com/manual/gh_pr_create">gh pr create</a> command since <a href="https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/using-github-cli-in-workflows">GitHub Actions now support GitHub CLI natively</a>.<br>For the <em>export Jira ticket list</em> task, we have been exporting a list of the Jira tickets that have some related commit inside the release branch by using Atlassian REST API. This task could also be migrated to GitHub Actions without many problems. Another point of view, could be to export a list of merged PRs instead of Jira ticket list, since there are some PRs that are not attached to any Jira ticket, they could be missed during the monkey testing phase.</li><li>announce the app version and Jira ticket list on Android team’s slack channel: This can be integrated into the workflow, with an automatic Slack announcement once the task is complete.</li><li>deploy Internal testing version app: Similar to the debug version, all subtasks can be migrated to a GitHub Actions workflow.</li><li>create Confluence document with release note information from clipboard: Instead of manually create the document on Confluence, it would be interesting to be able to create it automatically when the previous workflow has finished. Looks like a <a href="https://github.com/marketplace/actions/publish-confluence">third party action</a> or using the <a href="https://developer.atlassian.com/server/confluence/confluence-rest-api-examples/">Confluence API</a> could work for our use case.</li><li>check Internal testing version is being reviewed in Google Play Console: Currently we check this manually, and doesn’t look like there is any direct solution. One workaround could add it as last step in the previous flow and use <a href="https://developers.google.com/android-publisher#publishing">Publish API</a> from Google Play Developer API which has <a href="https://developers.google.com/android-publisher/api-ref/rest/v3/edits.tracks/get">edit.tracks</a> endpoint that returns a <a href="https://developers.google.com/android-publisher/api-ref/rest/v3/edits.tracks#Track">track</a> and its <a href="https://developers.google.com/android-publisher/api-ref/rest/v3/edits.tracks#Release">releases</a> including a <a href="https://developers.google.com/android-publisher/api-ref/rest/v3/edits.tracks#Status">status</a>. Another solution would be using a third party release tracking tool that allows integration on Slack.</li></ul><p>Summing it up, this phase could be fully executed remotely with some parts automatized, having three main steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*Ks5SuqEb7jvWaSIA5IoIXA.png" /></figure><ul><li>code freeze announcement: automated</li><li>deploy minified debug version app: manually triggered by <em>workflow_dispatch</em> from GitHub Actions</li><li>deploy Internal testing version app: manually triggered by <em>workflow_dispatch</em> from GitHub Actions</li></ul><p>To further improve automation, we could trigger deployments on a schedule. However, it could be a problem during holidays or if we want to skip a release during a specific week, so having some kind of actionable trigger like a button from a slack app asking if we want to perform a release for the current week and then trigger the actual GitHub Actions workflows, would be an ideal implementation.</p><h4>Pre-submission test (Android team)</h4><p>In this phase, all Android team members gather for monkey testing to ensure the main parts of the application are bug-free before handing it over to QA. This step was added to prevent dummy bugs from reaching QA, thereby saving time. Any critical bug found results in a hotfix applied to the release branch, requiring a version code bump for a new Internal Testing version.<br>We are currently integrating a third-party tool for automated integration tests, which will further streamline this phase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*657xGHh9g52xQe6-FROoJg.png" /></figure><h4>After pre-submission test</h4><p>After the Android team’s testing, we submit a new minified debug version for QA. This could also be handled by a GitHub Actions workflow with a <em>workflow_dispatch</em> trigger event.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*fRpV40dMv_bJwtO4u2LcBQ.png" /></figure><h4>During pre-submission QA</h4><p>Similar to the <em>Pre-submission test (Android team)</em> step, if QA finds a critical bug, a hotfix is applied to the release branch, requiring another deployment. We reuse the deployment workflow from earlier steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*JoDujnIB0pZdaXbO7bcUKw.png" /></figure><h4>After pre-submission QA</h4><p>Once QA is complete, we proceed with app submission. <br>Since we are already using <a href="https://github.com/Triple-T/gradle-play-publisher">gradle-play-publisher</a> for publishing the app to Google Play Console, we could take advantage of its <a href="https://github.com/Triple-T/gradle-play-publisher?tab=readme-ov-file#promoting-artifacts">Promoting artifacts</a> CLI feature which would allow us to promote from internal track to production one with a GitHub Actions workflow by using <em>workflow_dispatch</em> event trigger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*AEt_k_pTqZdgorvyYzYFzA.png" /></figure><h4>Release day</h4><p>On release day, there’s not much room for further automation. However, we could create a GitHub Actions workflow that is triggered by production release changes from Google Play Console with <a href="https://docs.github.com/en/actions/writing-workflows/choosing-when-your-workflow-runs/events-that-trigger-workflows#repository_dispatch">repository_dispatch</a>, which then notifies stakeholders of the release status.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*60OfzcxvktHbSHTXUWVM-A.png" /></figure><h4>After two days</h4><p>We monitor for critical bugs in Crashlytics. If everything looks good, we perform a full release. No changes are needed here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*_2F96v_Qv6h1_oEFh3iawA.png" /></figure><h3>Conclusion</h3><p>Transitioning from manual and local release process to an automated one using GitHub Actions workflows have many challenges. Among these challenges are the difficulties of integrating existing manual tasks into automated workflows, ensuring compatibility with our current infrastructure, and maintaining flexibility during unexpected scenarios, such as holidays or skipped releases. It is crucial to identify key manual processes that are time-consuming or error-prone and target them for early automation. Ultimately, while a fully automated process may not be entirely feasible, the gradual adoption of automation will yield significant benefits in efficiency, consistency, and reduced human error, making the overall release process at Eureka more robust and scalable. <br>In conclusion, the journey towards an automated release process is incremental, involving strategic planning, overcoming challenges, and continuous improvement, but the potential benefits make it a worthy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f93002f4c95" width="1" height="1" alt=""><hr><p><a href="https://medium.com/eureka-engineering/improving-android-release-process-at-eureka-pairs-app-1f93002f4c95">Improving Android release process at Eureka (Pairs app)</a> was originally published in <a href="https://medium.com/eureka-engineering">Pairs Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evolve Unidirectional Data Flow a.k.a MVI into MVVM + Jetpack Compose]]></title>
            <link>https://medium.com/eureka-engineering/evolve-unidirectional-data-flow-a-k-a-mvi-into-mvvm-jetpack-compose-e6858a767290?source=rss-6928ac19c493------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6858a767290</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[unidirectional-data-flow]]></category>
            <category><![CDATA[mvi]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[David Santos]]></dc:creator>
            <pubDate>Mon, 06 Dec 2021 02:41:52 GMT</pubDate>
            <atom:updated>2021-12-07T02:50:13.418Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*ZFCpJT49M6v0ZTe4QeOQ7Q.png" /></figure><h4>Migrate from the most overrated Android architecture to a simpler MVVM with the help of Jetpack Compose</h4><p><em>This is the December 7 article for </em><a href="https://qiita.com/advent-calendar/2021/eureka"><em>Eureka’s 2021 Advent Calendar</em></a><em>.</em></p><h3>Introduction</h3><p>After the inspiration of <a href="https://medium.com/u/7a8d96da8cb6">Gabor Varadi</a> reddit and medium posts regarding Unidirectional Data Flow a.k.a MVI, made me open my eyes and decided to try to simplify my coding experience by using MVVM and add Jetpack Compose to the recipe to make it hot 🔥.</p><p>Some reasons why it is not advisable to use MVI since it add nothing but complexity described by Gabor Varadi:</p><blockquote>It unnecessarily restricts the implementation detail of a screen model to be at most 1 mutable property</blockquote><blockquote>This makes it impossible to apply transformations to said individual properties, reducers are restrictive in this regard (and highly complex, as they manage <em>all</em> aspects of the screen, even if they are independent)</blockquote><blockquote>As all transformations apply to all properties, this makes changes made to the screen coupled: an update to an EditText triggering a data load can delay the processing of an independent event on an independent view component, causing performance and UX responsivity problems</blockquote><blockquote>The single mutable property adds requirement of copying deeply nested objects, that would otherwise not even be needed <em>at all</em></blockquote><blockquote>Both <a href="https://medium.com/androiddevelopers/data-binding-lessons-learnt-4fd16576b719">databinding</a> and compose can detect better that “one particular property changed” if other properties don’t trigger the same change on the same observer (you can theoretically export only a subset combined if necessary)</blockquote><blockquote>While MVI might be forcing you to build a state machine for the screen where all state is global, this can be overhead when a state machine isn’t actually needed</blockquote><blockquote>And most importantly,</blockquote><blockquote>combining all data, state, and transient state in a single mutable property makes state persistence hard, as you only want to save/restore the <strong>state</strong>, and the <strong>data</strong> is supposed to be asynchronously loaded based on switchMap, but in MVI this always happens inside the reducer, rather than merely a <em>switchMap</em></blockquote><h3>Purpose of this article</h3><p>The main purpose of this article is to evolve the current Unidirectional Data Flow architecture <a href="https://github.com/DavidEure/unidirectional-arch/tree/main">project</a> to a simpler one (MVVM) with the help of Jetpack Compose, so it would be easier to maintain and read for other developers. <br>Finally test edge cases and try to solve possible problems.</p><h3>Scope</h3><ul><li>Migration to MVVM architectural pattern</li><li>Use of Jetpack Compose</li></ul><h3>Out of scope</h3><ul><li>Network request</li><li>Error handling</li><li>Dependency Injection</li><li>Multi module project</li><li>Navigation Jetpack</li></ul><h3>Application specification</h3><p>You can find a description of the application specification on <a href="https://medium.com/eureka-engineering/android-unidirectional-architecture-with-stateflow-f5b2dda5ae73">this article</a>.</p><h3>Migration to MVVM</h3><p>Steps performed for the migration.</p><p>Remove <em>SharedFlow&lt;Actions&gt;</em> and use ViewModel public methods instead for communication between Fragment and ViewModel. Since events from UI would call ViewModel methods and <em>GreetingAction</em> will also be removed, <em>handleActions</em> is not necessary<em>.</em></p><pre>setOnClickListener <strong>{<br>     </strong>viewModel.greet<em>(</em>nickname?.<em>text</em>.<em>toString())<br> </em><strong>}</strong></pre><p>Separate the one StateFlow&lt;State&gt;property into individual properties and combine them with the help of <a href="https://github.com/Zhuinden/flow-combinetuple-kt"><strong>combineTuple</strong></a> to create an immutable state.</p><pre>private val isLoading = <em>MutableStateFlow(</em>false<em>)<br></em>private val successMessage = savedStateHandle.getLiveData<em>(</em>&quot;successMessage&quot;, &quot;&quot;<em>)<br></em>private val failureMessage = savedStateHandle.getLiveData<em>(</em>&quot;failureMessage&quot;, &quot;&quot;<em>)</em></pre><pre>val state = <em>combineTuple(<br>    </em>isLoading,<br>    successMessage.<em>asFlow()</em>,<br>    failureMessage.<em>asFlow()<br>)</em>.<em>map </em><strong>{ </strong><em>(</em>isLoading, successMessage, failureMessage<em>) </em><strong>-&gt;<br>    </strong>GreetingViewState<em>(<br>        </em>isLoading,<br>        successMessage,<br>        failureMessage<br>    <em>)<br></em><strong>}</strong></pre><p>After this change the following code becomes shorter and much simpler</p><pre>fun greet<em>(</em>nickname: String<em>) </em>= <em>viewModelScope</em>.<em>launch </em><strong>{<br>    </strong>if <em>(</em>nickname.<em>isBlank()) {<br>        </em>failureMessage.<em>value </em>= &quot;Please write your nickname&quot;<br>        successMessage.<em>value </em>= &quot;&quot;<br>    <em>} </em>else <em>{<br>        </em>isLoading.value = true<br>        failureMessage.<em>value </em>= &quot;&quot;<br>        successMessage.<em>value </em>= &quot;&quot;</pre><pre>        val message = GreetingRepositoryImpl.getMessage<em>(</em>nickname<em>)<br>        infoWorkingIn(</em>&quot;Greet Action: finished&quot;<em>)<br>        </em>isLoading.value = false<br>        successMessage.<em>value </em>= message<br>    <em>}<br></em><strong>}</strong></pre><p>Since now we are using individual properties with <em>savedStateHandle</em>, there is no need to make <em>GreetingState</em> extend from Serializable.</p><pre>data class GreetingViewState<em>(<br>    </em>val isLoading: Boolean,<br>    val successMessage: String,<br>    val failureMessage: String<br><em>)</em></pre><p>As bonus, with the recent release of <a href="https://developer.android.com/jetpack/androidx/releases/lifecycle#2.4.0">androidx.lifecycle:lifecycle-*:2.4.0</a> we can clean up this code part</p><pre>override fun onStart<em>() {<br>    </em>super.onStart<em>()<br>    </em>uiStateJob = <em>lifecycleScope</em>.<em>launch </em><strong>{<br>        </strong>viewModel.state.collect <strong>{ </strong>state <strong>-&gt; </strong>handleState<em>(</em>state<em>) </em><strong>}<br>    }<br></strong><em>}</em></pre><pre>override fun onStop<em>() {<br>    </em>uiStateJob?.cancel<em>()<br>    </em>super.onStop<em>()<br>}</em></pre><p>by using <strong>flowWithLifecycle</strong>, it will become</p><pre>override fun onCreate<em>(</em>savedInstanceState: Bundle?<em>) {<br>    </em>super.onCreate<em>(</em>savedInstanceState<em>)<br>    lifecycleScope</em>.<em>launch </em><strong>{<br>        </strong>viewModel.state<br>            .<em>flowWithLifecycle(lifecycle</em>, Lifecycle.State.<em>STARTED)<br>            </em>.collect <strong>{ </strong>state <strong>-&gt; </strong>handleState<em>(</em>state<em>) </em><strong>}<br>    }<br></strong><em>}</em></pre><h3>Use of Jetpack Compose</h3><p>Instead of using a full Compose screen by replacing the Fragment, I decided to integrate it into the current Fragment.</p><p>I have already created the composables for every UI part and integrate it on the Fragment as follows. You can find the detail implementation of UI composable elements in the repository.</p><pre>super.onViewCreated<em>(</em>view, savedInstanceState<em>)<br></em>view.findViewById<em>&lt;</em>ComposeView<em>&gt;(</em>R.id.<em>compose_view)</em>.<em>apply </em><strong>{<br>    </strong>setViewCompositionStrategy<em>(</em>ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed<em>)<br>    </em>setContent <strong>{ </strong><em>Greeting(</em>viewModel<em>) </em><strong>}<br>}</strong></pre><p><strong>DisposeOnViewTreeLifecycleDestroyed </strong>composition strategy was used to match compose lifecycle with Fragment lifecycle.</p><p>As you can see <em>viewModel</em> is passed to <em>Greeting</em> composable element since it will recompose when state changes, so we don’t need this part anymore:</p><pre><em>lifecycleScope</em>.<em>launch </em><strong>{<br>    </strong>viewModel.state<br>        .<em>flowWithLifecycle(lifecycle</em>, Lifecycle.State.<em>STARTED)<br>        </em>.collect <strong>{ </strong>state <strong>-&gt; </strong>handleState<em>(</em>state<em>) </em><strong>}<br>}</strong></pre><p>If we want to safe collect flow in Jetpack Compose we need to use <a href="https://developer.android.com/reference/kotlin/androidx/compose/runtime/package-summary#collectasstate">Flow.collectAsState</a> which represents the values as <a href="https://developer.android.com/reference/kotlin/androidx/compose/runtime/State">State&lt;T&gt;</a> to be able to update Compose UI.</p><p>We also need to use Flow.flowWithLifecycle since flow producer is still active and can waste resources when app is on background.</p><p>Finally, we need to <em>remember</em> the flow that is aware of the lifecycle with <em>viewModel.state</em> and <em>lifecycleOwner </em>as keys to always use the same flow unless one of the keys change.</p><p>After applying all these changes to <em>Greeting</em> composable would like something like this</p><pre>@Composable<br>fun Greeting<em>(</em>viewModel: GreetingViewModel, modifier: Modifier = Modifier<em>) {<br>    </em>val lifecycleOwner = <em>LocalLifecycleOwner</em>.current<br>    val stateLifecycleAware = <em>remember(</em>viewModel.state, lifecycleOwner<em>) </em><strong>{<br>        </strong>viewModel.state.<em>flowWithLifecycle(</em>lifecycleOwner.<em>lifecycle</em>, Lifecycle.State.<em>STARTED)<br>    </em><strong>}</strong></pre><pre><strong>    </strong>val state by stateLifecycleAware.<em>collectAsState(</em>GreetingViewState<em>())</em></pre><p>Since we want to use reusable composables, I have exposed both a stateful and a stateless version of the same <em>Greeting</em> composable. The above <em>Greeting c</em>omposable is the one which holds the state (stateful), which calls the stateless composable version. If you want to know more about this topic, please read <a href="https://developer.android.com/jetpack/compose/state#stateful-vs-stateless">Stateful versus stateless</a> and <a href="https://developer.android.com/jetpack/compose/state#state-hoisting">State hoisting</a>.<br>Stateless composable’s call inside the stateful composable:</p><pre><em>Greeting(<br>    </em>state = state,<br>    onGreetClick = <strong>{ </strong>viewModel.greet<em>() </em><strong>}</strong>,<br>    onNextClick = onNextClick,<br>    onNickNameChange = <strong>{ </strong>viewModel.onNickNameChange<em>(</em><strong>it</strong><em>) </em><strong>}</strong>,<br>    modifier = modifier<br><em>)</em></pre><ul><li>state: flow collected as <a href="https://developer.android.com/reference/kotlin/androidx/compose/runtime/State">State&lt;T&gt;</a>. Stateless <em>Greeting</em> will recompose the UI affected elements on state changes.</li><li>onGreatClick: delegates greet button click event to the composable’s caller.</li><li>onNextClick: delegates next float action button click event to the composable’s caller.</li><li>onNickNameChange: since we used <a href="https://developer.android.com/jetpack/compose/state#state-hoisting">state hoisting</a>, nickname input field text change event is moved to the composable’s caller which call <em>ViewModel</em> method provoking a change on the state. Once the state is changed the stateless <em>Greeting </em>composable will recompose only the affected UI elements, in this case the nickname input field.<br>One of the ways to accomplish the state hoisting is adding a new nickname field into the <em>ViewModel</em> and <em>GreetingViewState.</em></li></ul><pre>private val nickname = savedStateHandle.getLiveData<em>(</em>&quot;nickname&quot;, &quot;&quot;<em>)</em></pre><pre>val state = <em>combineTuple(<br>    </em>isLoading,<br>    nickname.<em>asFlow()</em>,<br>    successMessage.<em>asFlow()</em>,<br>    failureMessage.<em>asFlow()<br>)</em>.<em>map </em><strong>{ </strong><em>(</em>isLoading, nickname, successMessage, failureMessage<em>) </em><strong>-&gt;<br>    </strong>GreetingViewState<em>(<br>        </em>isLoading,<br>        nickname,<br>        successMessage,<br>        failureMessage<br>    <em>)<br></em><strong>}</strong></pre><p>Something I wanted to make notice is that we are not using Navigation Compose to keep the article as simple as possible. So we needed to move next button click event to outside of the stateful <em>Greeting</em> composable to be able to navigate with Fragment navigation controller.</p><pre>setContent <strong>{<br>    </strong><em>Greeting(<br>        </em>viewModel = viewModel,<br>        onNextClick = <strong>{ </strong>view.<em>findNavController()</em>.navigate<em>(</em>R.id.<em>to_otherFragment) </em><strong>}<br>    </strong><em>)<br></em><strong>}</strong></pre><h3>Edge cases</h3><p>Let’s start the interesting part!</p><h4>Interruptions</h4><ul><li>Going to background while loading and wait</li></ul><p>Thanks to <strong>flowWithLifecycle</strong> the flow is not being consumed when app is on background, so state is not changed until flow is consumed again when going back to foreground.</p><ul><li>Rotation while loading</li></ul><p>UI is recomposed with the latest state, so no problems here!</p><ul><li>Navigation to next view (Fragment) while loading</li></ul><p>Since we are storing the state into ViewModel and it is not cleared until Fragment is totally destroyed, when remote call is completed, the result will be saved as LiveData value, then going back to the first screen will consume latest state making recompose UI.</p><h4>Process death</h4><p>As you can see on the previous code, this time I have decided to use LiveData properties derived from SavedStateHandle for every piece of data that I wanted to keep, convert them as Flow to combine in one view state. This way we have the best of each world: SavedStateHandle + Flow operators.</p><pre>private val isLoading = <em>MutableStateFlow(</em>false<em>)<br></em>private val nickname = savedStateHandle.getLiveData<em>(</em>&quot;nickname&quot;, &quot;&quot;<em>)<br></em>private val successMessage = savedStateHandle.getLiveData<em>(</em>&quot;successMessage&quot;, &quot;&quot;<em>)<br></em>private val failureMessage = savedStateHandle.getLiveData<em>(</em>&quot;failureMessage&quot;, &quot;&quot;<em>)<br><br></em>val state = <em>combineTuple(<br>    </em>isLoading,<br>    nickname.<em>asFlow()</em>,<br>    successMessage.<em>asFlow()</em>,<br>    failureMessage.<em>asFlow()<br>)</em>.<em>map </em><strong>{ </strong><em>(</em>isLoading, nickname, successMessage, failureMessage<em>) </em><strong>-&gt;<br>    </strong>GreetingViewState<em>(<br>        </em>isLoading,<br>        nickname,<br>        successMessage,<br>        failureMessage<br>    <em>)<br></em><strong>}</strong></pre><p>This allows us to save the state and recompose UI even after process death.<br>Another option could be use <em>rememberSaveable</em> instead of using a ViewModel to host our state or part of it.</p><blockquote>rememberSaveable automatically saves any value that can be saved in a Bundle.</blockquote><h3>Conclusion</h3><p>Looks like the code has become simpler and easy to follow up without the different <em>Actions</em> and <em>handleActions</em> logic. We have a less (unnecessary) restricted architecture and less boilerplate code.</p><p>Now, every singular property is independent which allows granular updates without the unneeded complexity such as copying deeply nested objects. <br>With the help of <em>combine</em>, we retain reactive updates and it also allows us to apply operators like <em>debounce()</em> in individual properties instead of apply it to the global state.</p><p>I have to mention that we have migrated the Unidirectional Data Flow architecture we had to MVVM but by adding Jetpack Compose, we are using Unidirectional Data Flow. Compose is build off the standard of a UDF and it is expected that this paradigm is adhered to for proper implementation of Compose.</p><p>The only difficulty that I could think of this approach is the learning curve of the new paradigm (correctly) coding with Jetpack Compose.</p><h3>Repository</h3><p><a href="https://github.com/DavidEure/unidirectional-arch/tree/mvvm_compose">https://github.com/DavidEure/unidirectional-arch/tree/mvvm_compose</a></p><h3>Reference links</h3><ul><li><a href="https://developer.android.com/jetpack/compose/state">https://developer.android.com/jetpack/compose/state</a></li><li><a href="https://www.reddit.com/r/androiddev/comments/om4lng/what_are_the_things_you_dislike_the_most_about/h5kl68e/">https://www.reddit.com/r/androiddev/comments/om4lng/what_are_the_things_you_dislike_the_most_about/h5kl68e/</a></li><li><a href="https://www.reddit.com/r/androiddev/comments/om4lng/what_are_the_things_you_dislike_the_most_about/h5kl68e/">https://www.reddit.com/r/androiddev/comments/om4lng/what_are_the_things_you_dislike_the_most_about/h5kl68e/</a></li><li><a href="https://medium.com/androiddevelopers/a-safer-way-to-collect-flows-from-android-uis-23080b1f8bda">https://medium.com/androiddevelopers/a-safer-way-to-collect-flows-from-android-uis-23080b1f8bda</a></li><li><a href="https://medium.com/captech-corner/jetpack-compose-concepts-every-developer-should-know-5bcb47914542">https://medium.com/captech-corner/jetpack-compose-concepts-every-developer-should-know-5bcb47914542</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6858a767290" width="1" height="1" alt=""><hr><p><a href="https://medium.com/eureka-engineering/evolve-unidirectional-data-flow-a-k-a-mvi-into-mvvm-jetpack-compose-e6858a767290">Evolve Unidirectional Data Flow a.k.a MVI into MVVM + Jetpack Compose</a> was originally published in <a href="https://medium.com/eureka-engineering">Pairs Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android unidirectional architecture with StateFlow]]></title>
            <link>https://medium.com/eureka-engineering/android-unidirectional-architecture-with-stateflow-f5b2dda5ae73?source=rss-6928ac19c493------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5b2dda5ae73</guid>
            <category><![CDATA[mvi]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[unidirectional-data-flow]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[flow-state]]></category>
            <dc:creator><![CDATA[David Santos]]></dc:creator>
            <pubDate>Sun, 06 Dec 2020 23:46:47 GMT</pubDate>
            <atom:updated>2020-12-21T02:26:16.297Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android unidirectional architecture with StateFlow and SharedFlow</h3><h3>Introduction</h3><p>There are many ways to name this architecture, Unidirectional data flow, MVI, Redux but all these names are making reference to the same or similar concept: Create a single source of truth and a unidirectional information flow. <br>By the way, MVI (Model View Intent) might confuse some people because Intent is already used in Android with another meaning. In my opinion “Unidirectional architecture” is better naming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/0*M2GmQq01vCgRcNFb" /><figcaption>An example of how it could be (image from <a href="https://proandroiddev.com/android-unidirectional-state-flow-without-rx-596f2f7637bb">https://proandroiddev.com/android-unidirectional-state-flow-without-rx-596f2f7637bb</a>)</figcaption></figure><h3>Purpose of this article</h3><p>The main purpose of this article is to make a simple implementation of this architecture with the recent StateFlow from Kotlin, test edge cases and try to solve possible problems. <br>There are many articles about this architecture on the Internet but I think it would be interesting to try edge use cases, see how we could approach and solve possible problems.</p><h3>Scope</h3><ul><li>Unidirectional flow architecture</li><li>Use StateFlow instead of LiveData for binding ViewModel with View</li></ul><h3>Out of scope</h3><ul><li>Network request</li><li>Error handling</li><li>Dependency Injection</li><li>Clean architecture</li><li>Multi module project</li><li>Navigation Jetpack</li><li>Integrate with Compose Jetpack</li></ul><h3>Architecture implementation decisions</h3><p>Some implementations use a Store as a singleton for the whole application state but I prefer to have a concrete Store for one View so I will use ViewModel as Store and bind it to a single screen, so every screen will have its own Store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4yi5FXCaoTScux8i.jpeg" /><figcaption>Each screen updates on a Store’s change (image from <a href="https://android.jlelse.eu/how-flux-saved-my-life-4cb59a5e112a">https://android.jlelse.eu/how-flux-saved-my-life-4cb59a5e112a</a>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*V_Vai9jufomVmWAIrRiZzQ.png" /><figcaption>Each screen updates on its own Store’s change</figcaption></figure><p>There are cases where we would like to use a Store like Notification Store among different screens or features. In that case my approach would be to create a manager object as singleton instead of Store and register the specific Store to this manager so it can receive the notifications and bypass it to the view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*kYRQkhu0g3E1-sCwWuL6GQ.png" /><figcaption>Each screen updates on its own Store’s change with Notification Manager</figcaption></figure><p>Many implementations use a reducer function to generate a new state from the current one + action/intent but in this article I wanted to keep it as sample as possible so I will not implement it as a reducer function.</p><p>The communication between View and ViewModel (Store) is done by using a SharedFlow for Actions and StateFlow for view State.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*uxAlZh18Cn6SaOZuf07gEQ.png" /></figure><p>So we have a SharedFlow and StateFlow on the ViewModel:</p><pre><em>val </em>actionFlow = <em>MutableSharedFlow</em>&lt;GreetingAction&gt;()<br><em>private val </em>mutableState = <em>MutableStateFlow</em>(GreetingState(<em>false</em>, &quot;&quot;, &quot;&quot;))<br><em>val </em>state: <em>StateFlow</em>&lt;GreetingState&gt;<br>    <em>get</em>() = mutableState</pre><p>And handling the actions sent by the View</p><pre><em>init </em>{<br>    <em>viewModelScope</em>.<em>launch </em>{<br>        handleActions()<br>    }<br>}</pre><p>On the View side we will emit a new Action trough the SharedFlow whenever is necessary, for instance on click button event.</p><pre>viewModel.actionFlow.emit(GreetingAction.Greet(nickname?.text.<em>toString</em>()))</pre><p>And collect view State from ViewModel using the StateFlow.</p><pre><em>override fun </em>onViewCreated(view: View, savedInstanceState: Bundle?) {<br>    ...<br>    <em>lifecycleScope</em>.<em>launch </em>{<br>        viewModel.state.collect { state -&gt; handleState(state) }<br>    }<br>}</pre><h3>Points to be careful with StateFlow</h3><ul><li>Initial value is required.</li><li>With LiveData.observe() automatically unregisters the consumer when the view goes to the STOPPED state, whereas collecting from a StateFlow or any other flow does not. We will see what happens because of this later on this article.</li><li>Values in StateFlow are conflated<strong> </strong>so it will not dispatch the same state in a row (similar to distinct on RxJava), so depending on your use case consider using SharedFlow instead.</li></ul><h3>Application specification</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*XZ6OZOLoSBBVKYHpo5Dafw.gif" /></figure><p>The application basically has two screens (Fragments), one for greeting and another empty just to test edge cases.</p><p>The greeting screen simulates an API request using a delay function from Kotlin coroutines. User’s nickname input is sent, after a while a message from a remote source is received.</p><h3>Edge cases</h3><p>Let’s start the interesting part!</p><h4>Interruptions</h4><ul><li>Going to background while loading and wait</li></ul><p>View state (StateFlow) is being consumed even when background state.<br>This behavior could waste resources when is not necessary besides is not recommendable to access to view elements while the app is on background since it could provoke crash errors.<br>Possible solution:</p><pre><em>lifecycleScope</em>.launchWhenStarted {<br>    viewModel.state.collect { state -&gt; handleState(state) }<br>}</pre><p>With <em>launchWhenStarted</em> will create a coroutine for collecting StateFlow when the view is at least in the Started state and will stop the coroutine (pause collecting) when the view moves to the Stopped state. LiveData behaves like this out of the box.</p><p>But after trying this approach, it created a new problem. As many times as the view enters to the Started state, coroutines are being created. So If we navigate to another view and come back to previous view, a new coroutine will be created thus view state will be collected twice and so on.<br>Solution to this problem:</p><pre><em>override fun </em>onStart() {<br>    <em>super</em>.onStart()<br>    uiStateJob = <em>lifecycleScope</em>.<em>launch </em>{ <br>        viewModel.state.collect { state -&gt; handleState(state) }<br>    }<br>}<br><br><em>override fun </em>onStop() {<br>    uiStateJob?.cancel()<br>    <em>super</em>.onStop()<br>}</pre><p>Basically it manually stops collecting the StateFlow and replace the previous Job with a new one when entering to Started state.</p><ul><li>Rotation while loading</li></ul><p>Since we are using StateFlow, it will collect the last UI state value, and recreate the view with it. No problems here!</p><ul><li>Navigation to next view (Fragment) while loading</li></ul><p>Since ViewModel is not cleared until Fragment is totally destroyed, when remote call is completed, result will stored into StateFlow, then going back to the first screen will collect last UI state and show the message.</p><h4>Process death</h4><p>Some time ago SavedStateHandle was released with the purpose of easily keep data even after process death. It is integrated with ViewModel and works quite well with LiveData using the method getLiveData. So integrating it to StateFlow, becomes a little bit unnatural but you can work around getting the saved state when ViewModel is created and set the new values in parallel when emitting them using StateFlow.</p><pre><em>init </em>{<br>    ...<br><br>    savedStateHandle.get&lt;GreetingState&gt;(&quot;state&quot;)?.<em>let </em>{ savedState -&gt;<br>        mutableState.value = savedState<br>    }<br>}</pre><pre>...</pre><pre>savedStateHandle[&quot;state&quot;] = mutableState.value.copy(<br>    isLoading = <em>true</em>,<br>    successMessage = &quot;&quot;,<br>    failureMessage = &quot;&quot;<br>)</pre><h3>Conclusion</h3><p>Looks like StateFlow can be used instead of LiveData, but we still have to perform some workarounds to get the same behavior as LiveData.</p><p>The good part is that StateFlow has more operators than LiveData, close to RxJava operators. Also it is native Kotlin so we are decoupling from Android SDK and maybe getting closer to KMM (Kotlin multiplatform mobile) in the case we use Store object independent from ViewModel.</p><p>I can not strongly recommend either one or other, I think it depends on which is your app architecture. If you are using ViewModel as Store or binding component for your Views, then probably LiveData fits better. But If you are using a pure Kotlin native Store approach then StateFlow could fit better. Also don’t forget you can transform a StateFlow to LiveData using <em>asLiveData()</em> method.</p><h3>Repository</h3><p><a href="https://github.com/DavidEure/unidirectional-arch/tree/main">https://github.com/DavidEure/unidirectional-arch/</a></p><h3>Reference links</h3><ul><li><a href="https://developer.android.com/kotlin/flow/stateflow-and-sharedflow">https://developer.android.com/kotlin/flow/stateflow-and-sharedflow</a></li><li><a href="https://developer.android.com/topic/libraries/architecture/viewmodel-savedstate">https://developer.android.com/topic/libraries/architecture/viewmodel-savedstate</a></li><li><a href="https://android.jlelse.eu/how-flux-saved-my-life-4cb59a5e112a">https://android.jlelse.eu/how-flux-saved-my-life-4cb59a5e112a</a></li><li><a href="https://docs.google.com/presentation/d/105QxLVF57nKV5Q1Yaw5Zyk7on5E-Q3Ewid6U-5M8I00/edit#slide=id.p">https://docs.google.com/presentation/d/105QxLVF57nKV5Q1Yaw5Zyk7on5E-Q3Ewid6U-5M8I00/edit#slide=id.p</a></li><li><a href="https://quickbirdstudios.com/blog/android-mvi-kotlin-coroutines-flow/">https://quickbirdstudios.com/blog/android-mvi-kotlin-coroutines-flow/</a></li><li><a href="https://levelup.gitconnected.com/stateflow-sharedflow-and-the-secret-bus-ba9978ad8453">https://levelup.gitconnected.com/stateflow-sharedflow-and-the-secret-bus-ba9978ad8453</a></li><li><a href="https://www.youtube.com/watch?v=ZP7BsG1mhyQ">https://www.youtube.com/watch?v=ZP7BsG1mhyQ</a></li><li><a href="https://www.youtube.com/watch?v=g10RWt_Ivok&amp;ab_channel=JohnWilker">https://www.youtube.com/watch?v=g10RWt_Ivok&amp;ab_channel=JohnWilker</a></li><li><a href="https://github.com/ashrafi/MVIFlow">https://github.com/ashrafi/MVIFlow</a></li><li><a href="https://proandroiddev.com/android-unidirectional-state-flow-without-rx-596f2f7637bb">https://proandroiddev.com/android-unidirectional-state-flow-without-rx-596f2f7637bb</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5b2dda5ae73" width="1" height="1" alt=""><hr><p><a href="https://medium.com/eureka-engineering/android-unidirectional-architecture-with-stateflow-f5b2dda5ae73">Android unidirectional architecture with StateFlow</a> was originally published in <a href="https://medium.com/eureka-engineering">Pairs Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>