<?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 Matías Del Bel on Medium]]></title>
        <description><![CDATA[Stories by Matías Del Bel on Medium]]></description>
        <link>https://medium.com/@matiasdelbel?source=rss-51e8f2d50f4f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PJ2oNW8wi-YemBKKMs01ow.png</url>
            <title>Stories by Matías Del Bel on Medium</title>
            <link>https://medium.com/@matiasdelbel?source=rss-51e8f2d50f4f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 16:51:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@matiasdelbel/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[Implementing a Simple Counter Screen with MVI]]></title>
            <link>https://medium.com/@matiasdelbel/implementing-a-simple-counter-screen-with-mvi-abf5750e0cba?source=rss-51e8f2d50f4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/abf5750e0cba</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mvi]]></category>
            <dc:creator><![CDATA[Matías Del Bel]]></dc:creator>
            <pubDate>Wed, 07 Jan 2026 15:35:36 GMT</pubDate>
            <atom:updated>2026-01-07T15:35:36.998Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we’ll implement a <strong>simple counter screen using the MVI (Model–View–Intent) architecture</strong> in Android.</p><p>Instead of writing all the boilerplate ourselves, we’ll rely on the <a href="https://github.com/buildkt/mvi">buildkt/mvi</a> library, which provides a clean and pragmatic MVI implementation.</p><p>You can find the <strong>complete working example</strong> here:<br> 👉 <a href="https://github.com/buildkt/mvi-samples">https://github.com/buildkt/mvi-samples</a></p><h4>What we’re building</h4><p>The screen consists of:</p><ul><li>A Text showing the current counter value</li><li>Two Buttons: Increment and Decrement.</li></ul><p>That’s enough to demonstrate the core ideas behind MVI without unnecessary complexity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*HdXbmQYe1WAZi9v0QIulww.png" /></figure><h4>Defining the Model (UI State)</h4><p>In MVI, the <strong>model</strong> represents the entire state of the screen at a given point in time. The UI is a pure function of this state.</p><p>For our counter screen, the state needs:</p><ul><li>The current counter value</li><li>A flag to enable or disable user interaction while an update is in progress.</li></ul><pre>data class CounterUiState(<br>    val counter: Int = 0,<br>    val isScreenEnabled: Boolean = true,<br>) </pre><p>This state is <strong>immutable</strong>. Every change produces a new instance, which makes the UI predictable and easy to reason about.</p><h4>Defining the intents</h4><p><strong>Intents</strong> represent actions that want to change the state.</p><p>They can be triggered by:</p><ul><li>The user (e.g. clicking a button)</li><li>The system (e.g. an async operation finishing)</li></ul><p>For this screen, we have three intents:</p><ol><li>The user wants to increment the counter</li><li>The user wants to decrement the counter</li><li>The storage layer reports that the counter has been updated.</li></ol><pre><br>sealed interface CounterIntent {<br><br>    @TriggersSideEffect<br>    data object IncrementCounter : CounterIntent<br><br>    @TriggersSideEffect<br>    data object DecrementCounter : CounterIntent<br><br>    @TriggersSideEffect<br>    data class CounterUpdated(val newValue: Int) : CounterIntent<br>}</pre><h4>Defining the View</h4><p>The <strong>view</strong> renders the current state and emits intents in response to user actions. It does <strong>not</strong> mutate state directly.</p><p>In Jetpack Compose, the view is simply a composable function:</p><pre>@Composable<br>fun CounterPane(<br>    state: CounterUiState,<br>    onIntent: (CounterIntent) -&gt; Unit,<br>    modifier: Modifier = Modifier,<br>) {<br>  /* ... */<br>  Text(text = state.counter.toString())<br>  /* ... */<br>  Button(<br>    onClick = { onIntent(CounterIntent.DecrementCounter) },<br>    text = &quot;Decrement&quot;,<br>  )<br>  Button(<br>    onClick = { onIntent(CounterIntent.IncrementCounter) },<br>    text = &quot;Increment&quot;,<br>  )<br>}</pre><p>Notice the key idea:</p><ul><li>The UI <strong>only reads</strong> from CounterUiState</li><li>The UI <strong>only writes</strong> by emitting CounterIntents</li></ul><h4>Defining the Reducer</h4><p>The <strong>reducer</strong> is a pure function that takes:</p><ul><li>The current state</li><li>An intent</li></ul><p>…and returns a <strong>new state</strong>.</p><pre><br>val counterReducer = Reducer&lt;CounterUiState, CounterIntent&gt; { state, intent -&gt;<br>    when (intent) {<br>        is CounterIntent.CounterUpdated -&gt; state.copy(<br>            isScreenEnabled = true,<br>            counter = intent.newValue<br>        )<br><br>        CounterIntent.DecrementCounter -&gt; state.copy(<br>            isScreenEnabled = false<br>        )<br><br>        CounterIntent.IncrementCounter -&gt; state.copy(<br>            isScreenEnabled = false<br>        )<br>    }<br>}</pre><p>Key points:</p><ul><li>The reducer contains <strong>no side effects</strong></li><li>It only describes how state evolves</li><li>Temporary UI states (like disabling buttons) are handled here</li></ul><h4>Handling Side Effects</h4><p>A <strong>side effect</strong> represents work that:</p><ul><li>Is not pure</li><li>Interacts with the outside world (database, network, disk, etc.)</li></ul><p>In our example, incrementing or decrementing the counter updates a repository and then emits a new intent once the operation completes.</p><p><strong>Decrement side effect</strong></p><pre>fun decrementCounter(<br>    counterRepository: CounterRepository<br>) = sideEffect&lt;CounterUiState, CounterIntent&gt; { state, _ -&gt;<br>    val newValue = state.counter - 1<br>    counterRepository.update(newValue)<br>    <br>    CounterIntent.CounterUpdated(newValue)<br>}</pre><p><strong>Increment side effect</strong></p><pre>fun incrementCounter(<br>    counterRepository: CounterRepository<br>) = sideEffect&lt;CounterUiState, CounterIntent&gt; { state, _ -&gt;<br>    val newValue = state.counter + 1<br>    counterRepository.update(newValue)<br><br>    CounterIntent.CounterUpdated(newValue)<br>}</pre><p>Side effects:</p><ul><li>Read the current state</li><li>Perform external work</li><li>Emit a <strong>new intent</strong> back into the system</li></ul><p>This keeps the unidirectional data flow intact.</p><h4>Wiring Everything with Jetpack Navigation</h4><p>buildkt/mvi provides an extension on NavGraphBuilder that makes integration with Jetpack Navigation straightforward.</p><pre>counterPane(<br>    navController = navController,<br>    route = COUNTER_ROUTE<br>) {<br>    reducer = counterReducer<br> <br>    sideEffects {<br>        decrementCounter = decrementCounter(counterRepository)<br>        incrementCounter = incrementCounter(counterRepository)<br>    }<br>}</pre><p>At this point, everything is connected:</p><ul><li>View → emits intents</li><li>Reducer → updates state</li><li>Side effects → perform work and emit new intents</li><li>State → re-renders the UI</li></ul><h4>Final Thoughts</h4><p>This small example shows the <strong>core strength of MVI</strong>:</p><ul><li>Clear separation of concerns</li><li>Predictable state changes</li><li>Easy-to-test logic</li><li>Explicit handling of side effects</li></ul><p>Even for a simple counter, the structure scales naturally to more complex screens with async flows, error handling, and multiple data sources.</p><p>If you want to explore further, check out the full sample repository:<br> 👉 <a href="https://github.com/buildkt/mvi-samples">https://github.com/buildkt/mvi-samples</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abf5750e0cba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Goodbye, MVI Boilerplate: Introducing BuildKt MVI, the Library That Writes Code for You]]></title>
            <link>https://medium.com/@matiasdelbel/goodbye-mvi-boilerplate-introducing-buildkt-mvi-the-library-that-writes-code-for-you-1d7467800e8f?source=rss-51e8f2d50f4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d7467800e8f</guid>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mvi]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Matías Del Bel]]></dc:creator>
            <pubDate>Tue, 16 Dec 2025 08:39:12 GMT</pubDate>
            <atom:updated>2025-12-16T08:39:12.256Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re an Android developer working with Jetpack Compose, you’ve probably been told that MVI (Model-View-Intent) is the way to go. And it often is!</p><p>The unidirectional data flow and clear separation of concerns make our apps predictable, testable, and easier to debug. But let’s be honest. For every screen we build, we write the same repetitive, soul-draining boilerplate:</p><ul><li>Create a ViewModel (for holding the state/model).</li><li>Create a ViewModelProvider.Factory to handle navigation arguments.</li><li>Manually create a StateFlow for the UI state.</li><li>Manually create a SharedFlow or Channel for one-shot UI events.</li><li>Write a NavGraphBuilder extension function for navigation.</li><li>Painstakingly extract navigation arguments from the SavedStateHandle.</li></ul><p>We do this over and over again. It’s tedious, error-prone, and it distracts us from what we actually want to build: great features. I got tired of this cycle. I thought, “There has to be a better way.”</p><p>Today, I’m happy to introduce the open-source release of BuildKt MVI, an annotation-driven MVI framework for Jetpack Compose that eliminates nearly all of this boilerplate.</p><h4>What is BuildKt MVI?</h4><blockquote>BuildKt MVI is a lightweight yet powerful framework that uses KSP (Kotlin Symbol Processing) to generate the full MVI scaffolding for each screen at compile time. Your job is to focus on business logic and UI. The framework takes care of the rest.</blockquote><p>Let’s see what that means in practice.</p><h4>The “Aha!” Moment: Before and After</h4><p>Imagine you’re building a simple profile screen. Without BuildKt MVI, your file structure for just one screen would look something like this:</p><pre>❌ ProfilePane.kt             // Your UI<br>❌ ProfileViewModel.kt        // The ViewModel<br>❌ ProfileViewModelFactory.kt // The factory for the ViewModel<br>❌ ProfileNavGraph.kt         // The NavGraphBuilder extension</pre><p>You’d spend a good chunk of time writing the plumbing inside those files just to get started. With BuildKt MVI, this is all you need:</p><pre>✅ ProfilePane.kt             // Your UI, annotated<br>✨ The rest is auto-generated!</pre><p>You write one file, add one annotation, and the framework generates the ViewModel, Factory, and NavGraphBuilder extension for you at compile time.</p><h4>How Does It Work? A 3-Step Guide</h4><p>Let’s build that profile screen in under 5 minutes.</p><ol><li><strong>Define Your State and Intent. </strong>This is pure business logic. What data does your screen need, and what can the user do?</li></ol><pre>data class ProfileUiState(<br>    val isLoading: Boolean = true,<br>    val userName: String = &quot;&quot;<br>)<br><br>sealed interface ProfileIntent {<br>    @TriggersSideEffect<br>    data object LoadUserName : ProfileIntent<br><br>    data class OnUserNameLoaded(val name: String) : ProfileIntent<br>}</pre><p>Notice the <strong>@TriggersSideEffect</strong> annotation. This tells the framework that <strong>LoadUserName</strong> will involve asynchronous work, like an API call.</p><p>2.<strong> Create and Annotate Your Composable. </strong>Create your Composable as you normally would, but add the <strong>@MviScreen</strong> annotation. This is the trigger for all the code generation.</p><pre>@MviScreen(<br>    uiState = ProfileUiState::class,<br>    intent = ProfileIntent::class<br>)<br>@Composable<br>fun ProfilePane(<br>    state: ProfileUiState,<br>    onIntent: (ProfileIntent) -&gt; Unit,<br>) {<br>    if (state.isLoading) {<br>        CircularProgressIndicator()<br>    } else {<br>        Text(&quot;Hello, ${state.userName}!&quot;)<br>    }<br>}</pre><p>The processor expects a state parameter and an onIntent callback to wire everything together. That’s it.</p><p>3. <strong>Implement the Logic in Your NavHost.</strong> BuildKt MVI generates a type-safe, DSL-based extension function for your NavGraphBuilder. You just need to fill in the blanks.</p><p>Take a look at the reducer, it is a pure function by design, responsible only for state transitions.</p><pre>NavHost(navController, startDestination = &quot;profilePane&quot;) {<br><br>    // KSP-generated function `profilePane`<br>    profilePane(navController = navController) {<br><br>        // The reducer is a pure function to update state<br>        reducer = { state, intent -&gt;<br>            when (intent) {<br>                is ProfileIntent.OnUserNameLoaded -&gt; {<br>                    state.copy(isLoading = false, userName = intent.name)<br>                }<br>                else -&gt; state<br>            }<br>        }<br><br>        // The side effects handle all async work<br>        sideEffects {<br>            loadUserName = sideEffect {<br>                // Simulate an API call<br>                delay(2000)<br>                // Return a new intent with the result<br>                newIntent(ProfileIntent.OnUserNameLoaded(&quot;Matias&quot;))<br>            }<br>        }<br>    }<br>}</pre><p>And you’re done! A fully functional, testable MVI screen with zero manual boilerplate.</p><p><strong>Navigation arguments?</strong> They’re handled too — just add a parameter with <strong>@NavArgument</strong> to your Composable.</p><h4>Why BuildKt MVI?</h4><ul><li>Focus on What Matters: Stop writing plumbing, start writing features.</li><li>Drastically Reduced Boilerplate: A single annotation replaces hundreds of lines of code.</li><li>Type-Safe by Design: Generated DSLs for reducers and side effects prevent runtime errors.</li><li>Built for Modern Android: Designed from the ground up for KSP and Jetpack Compose.</li><li>Scalable and Testable: Promotes a clean, decoupled architecture that’s easy to maintain and test.</li></ul><h4>Get Started Today!</h4><p>This project was born from real-world production pain, and it’s evolving in the open. Your feedback, issues, and ideas will directly shape its future.</p><p>BuildKt MVI is open-source and available on Maven Central.</p><p>I invite you to try it in your next project, read the documentation, and see how much time you can save.</p><p>Check it out on GitHub, give it a star if you find it useful, and feel free to open an issue or contribute!</p><p>GitHub Repo: <a href="https://github.com/buildkt/mvi">https://github.com/buildkt/mvi</a></p><p>Your feedback is invaluable. Let’s build better Android apps, faster, together.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d7467800e8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Moving from MVVM and MVI with Middleware to Pure MVI in Android]]></title>
            <link>https://medium.com/@matiasdelbel/moving-from-mvvm-and-mvi-with-middleware-to-pure-mvi-in-android-31b00a064051?source=rss-51e8f2d50f4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/31b00a064051</guid>
            <category><![CDATA[mvi]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Matías Del Bel]]></dc:creator>
            <pubDate>Wed, 03 Sep 2025 09:25:26 GMT</pubDate>
            <atom:updated>2025-09-03T09:25:26.517Z</atom:updated>
            <content:encoded><![CDATA[<p>In my previous articles, I explored implementing the same feature using <strong>MVVM</strong> and <strong>MVI with middleware</strong> in Android. Both approaches offered interesting insights: MVVM keeps state simple but can become verbose when managing side effects, while MVI with middleware centralizes side effects but adds complexity in wiring middleware layers.</p><ul><li><a href="https://medium.com/@matiasdelbel/implementing-a-review-flow-in-android-using-mvi-and-jetpack-compose-1b900f34fee8">Implementing a Review Flow in Android using MVI and Jetpack Compose</a></li><li><a href="https://medium.com/@matiasdelbel/implementing-a-review-flow-in-android-using-mvvm-and-jetpack-compose-fce217d138d5">Implementing a Review Flow in Android using MVVM and Jetpack Compose</a></li></ul><p>In this article, I want to go a step further and show a <strong>pure MVI approach</strong>, where state, intents, and side effects are fully decoupled, allowing for a more predictable and testable architecture.</p><p>If you want to check the full source code, please follow this link <a href="https://github.com/matiasdelbel/mvi-form-feedback">https://github.com/matiasdelbel/mvi-form-feedback</a></p><h3>The Core Idea of Pure MVI</h3><p>At its heart, <strong>MVI (Model-View-Intent)</strong> is about three things:</p><ol><li><strong>State</strong>: A single source of truth representing the UI.</li><li><strong>Intent</strong>: User or system actions that request state changes.</li><li><strong>Side Effects</strong>: One-off actions like navigation, showing a toast, or network requests.</li></ol><p>A pure MVI implementation ensures:</p><ul><li><strong>State is immutable</strong> and only updated via a reducer.</li><li><strong>Intents are the only way to request changes</strong>.</li><li><strong>Side effects are handled separately</strong>, possibly triggering new intents.</li></ul><h3>Implementing a Generic MVI ViewModel</h3><p>We can abstract the common patterns in a base ViewModel:</p><pre>abstract class ViewModel&lt;S, I : Any, E : Any&gt;(<br>    initialState: S,<br>    private val reducer: Reducer&lt;S, I, E&gt;,<br>    private val sideEffectHandler: SideEffectHandler&lt;S, I, E&gt;,<br>) : androidx.lifecycle.ViewModel() {<br><br>    private val _uiState = MutableStateFlow(initialState)<br>    val state: StateFlow&lt;S&gt; = _uiState<br>    <br>    private val _effects = MutableSharedFlow&lt;E&gt;(replay = 0, extraBufferCapacity = 1)<br>    val effects: SharedFlow&lt;E&gt; = _effects.asSharedFlow()<br>    <br>    fun onIntent(intent: I) {<br>        _uiState.value = reducer.reduce(_uiState.value, intent) { sideEffect -&gt;<br>            handleSideEffect(sideEffect)<br>        }<br>    }<br>    <br>    private fun handleSideEffect(sideEffect: E) {<br>        viewModelScope.launch {<br>            sideEffectHandler.handle(_uiState.value, sideEffect) { newIntent -&gt;<br>                onIntent(newIntent)<br>            }<br>        }<br>    }<br>}</pre><p>Key points:</p><ul><li>StateFlow exposes the <strong>current state</strong> for the UI.</li><li>SharedFlow handles <strong>one-off effects</strong>.</li><li>The <strong>reducer</strong> produces new state and optionally emits side effects.</li><li>The <strong>side effect handler</strong> can trigger additional intents asynchronously.</li></ul><blockquote><strong>Disclaimer:</strong><br>In this example, the ViewModel is used primarily as a convenient, lifecycle-aware holder for the state and logic. It doesn&#39;t contain any presentation logic itself — it simply wires together the reducer, initial state, and side effect handlers.</blockquote><h3>Reducers: Pure Functions for State Changes</h3><p>Reducers are <strong>pure functions</strong>: given a state and an intent, they return a new state.</p><pre>class ReviewReducer(private val reviewValidator: ReviewValidator) : Reducer&lt;ReviewUiState&lt;String&gt;, ReviewIntent, ReviewSideEffect&gt; {<br><br>    override fun reduce(<br>        state: ReviewUiState&lt;String&gt;,<br>        intent: ReviewIntent,<br>        throwSideEffect: (ReviewSideEffect) -&gt; Unit<br>    ): ReviewUiState&lt;String&gt; = when (intent) {<br>        is ReviewIntent.RatingSelected -&gt; state.copy(<br>            review = state.review?.copy(rating = intent.rating) ?: ReviewRatingUiState(rating = intent.rating),<br>            errors = reviewValidator.validate(state.review ?: ReviewRatingUiState(rating = intent.rating))<br>        )<br>        is ReviewIntent.DescriptionChanged -&gt; state.copy(<br>            review = state.review?.copy(description = intent.description) ?: ReviewRatingUiState(description = intent.description),<br>            errors = reviewValidator.validate(state.review ?: ReviewRatingUiState(description = intent.description))<br>        )<br>        ReviewIntent.SubmitReview -&gt; state.copy(<br>            review = state.review?.copy(synchronizing = true) ?: ReviewRatingUiState(synchronizing = true)<br>        )<br>        ReviewIntent.ReviewSubmitted -&gt; state.copy(<br>            review = state.review?.copy(synchronizing = false) ?: ReviewRatingUiState(synchronizing = false)<br>        )<br>    }<br>}</pre><p>Notice how <strong>all state updates are immutable</strong> and side effects are decoupled from the state itself.</p><h3>Side Effects: Async or One-Off Actions</h3><p>Side effects are <strong>isolated from the reducer</strong>, keeping state logic pure:</p><pre>class ReviewSideEffectHandler : SideEffectHandler&lt;ReviewUiState&lt;String&gt;, ReviewIntent, ReviewSideEffect&gt; {<br>    override suspend fun handle(<br>        state: ReviewUiState&lt;String&gt;,<br>        effect: ReviewSideEffect,<br>        onNewIntent: (ReviewIntent) -&gt; Unit<br>    ) {<br>        when (effect) {<br>            ReviewSideEffect.SubmitReview -&gt; {<br>                delay(2000) // Simulate network call<br>                onNewIntent(ReviewIntent.ReviewSubmitted)<br>            }<br>        }<br>    }<br>}</pre><p>Advantages:</p><ul><li><strong>Testable</strong>: You can unit-test side effect logic independently.</li><li><strong>Composable</strong>: Multiple handlers can be composed if needed.</li><li><strong>Predictable</strong>: Side effects never mutate state directly.</li></ul><h3>Benefits of Pure MVI</h3><ol><li><strong>Predictable State</strong>: Only reducers update state.</li><li><strong>Traceable Side Effects</strong>: All side effects are explicit and can trigger new intents.</li><li><strong>Composable &amp; Modular</strong>: Handlers and reducers can be reused across features.</li><li><strong>UI-Agnostic</strong>: The architecture works with Compose, XML, or even multi-platform targets.</li></ol><h3>Conclusion</h3><p>Pure MVI simplifies the mental model:</p><p><strong>Intent → Reducer → State → SideEffectHandler → New Intent</strong></p><p>By keeping reducers pure and side effects isolated, your Android applications gain <strong>predictability, testability, and modularity</strong>, which are especially valuable in complex flows like reviews, forms, or e-commerce checkout processes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31b00a064051" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing a Review Flow in Android using MVI and Jetpack Compose]]></title>
            <link>https://medium.com/@matiasdelbel/implementing-a-review-flow-in-android-using-mvi-and-jetpack-compose-1b900f34fee8?source=rss-51e8f2d50f4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b900f34fee8</guid>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[mvi]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Matías Del Bel]]></dc:creator>
            <pubDate>Wed, 30 Jul 2025 08:32:04 GMT</pubDate>
            <atom:updated>2025-07-30T08:32:04.259Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@matiasdelbel/implementing-a-review-flow-in-android-using-mvvm-and-jetpack-compose-fce217d138d5">first part of this series</a>, we implemented a simple review form using the MVVM pattern, Jetpack Compose, and Hilt. The goal was to show a clear, modular way to collect user feedback in an Android app.</p><p>In this second part, we’ll take a different route and explore how to implement the same feature using <strong>MVI (Model-View-Intent)</strong>. The MVI architecture offers better predictability, easier testing, and a more functional way to manage state. This approach is particularly useful when the number of states and events grows and you want to keep full control over the state evolution.</p><p>You can find the full implementation for the MVI example in this GitHub repository <a href="https://github.com/matiasdelbel/mvi-form-feedback">https://github.com/matiasdelbel/mvi-form-feedback</a>. Feel free to clone the project, explore the architecture, and adapt it to your own needs.</p><h3>Why MVI?</h3><p>The MVVM pattern is easy to understand and widely used, but it can lead to business logic being scattered across the ViewModel, use cases, and LiveData observers. With MVI, all state transitions are explicit and traceable, making it easier to debug, reason about, and test.</p><h4>Reusing the UI</h4><p>In this article, we’ll reuse the same Compose UI from the first part. The only thing that changes is how we manage state. If you haven’t read that article, it might be useful to check it out first.</p><h4>Dependency Injection with Hilt</h4><p>To keep things modular, we define a simple Hilt module to provide the reducer:</p><pre>@Module<br>@InstallIn(ViewModelComponent::class)<br>internal object ReviewModule {<br>    <br>    @Provides<br>    fun provideReviewReducer() = ReviewReducer(reviewValidator = ReviewValidator())<br>}</pre><h4>The State and Events</h4><p>We continue using the same ReviewUiState</p><pre>data class ReviewUiState(<br>    val item: ReviewItemUiState,<br>    val review: ReviewRatingUiState? = null,<br>    val errors: ReviewError? = null,<br>)<br><br>data class ReviewItemUiState(<br>    val itemId: String,<br>    val itemName: String,<br>    val shortDescription: String,<br>    val imageUrl: String,<br>)<br><br>data class ReviewRatingUiState(<br>    val rating: Int = 0,<br>    val description: String = &quot;&quot;,<br>    val maxRating: Int = 5,<br>    val synchronizing: Boolean = false,<br>)</pre><p>And for the events, instead of exposing multiple functions in the ViewModel, I opted to define a sealed interface that represents all possible user events in a single, type-safe way:ReviewEvent.</p><h4>The Reducer</h4><p>In MVI, a Reducer is a pure function that takes the current state and an event (or intent), and returns a new state. Here’s our implementation:</p><pre>class ReviewReducer(<br>    private val reviewValidator: ReviewValidator<br>) : Reducer&lt;ReviewUiState&lt;String&gt;, ReviewEvent&gt; {<br>       override fun invoke(state: ReviewUiState&lt;String&gt;, intent: ReviewEvent) = when (intent) {<br>        is ReviewEvent.RatingSelected -&gt; ...<br>        is ReviewEvent.DescriptionChanged -&gt; ...<br>        ReviewEvent.SubmitReview -&gt; ...<br>        ReviewEvent.ReviewSubmitted -&gt; ...<br>    }<br>}</pre><p>The Reducer is deterministic, side-effect free, and testable in isolation.</p><h4>The ViewModel</h4><blockquote><strong><em>Disclaimer:</em></strong><em><br> In this example, the </em><em>ViewModel is used primarily as a convenient, lifecycle-aware holder for the state and logic. It doesn&#39;t contain any presentation logic itself — it simply wires together the reducer, initial state, and middleware.</em></blockquote><blockquote><em>The architecture shown here is kept intentionally simple to focus on the core ideas of MVI. Much of the boilerplate is reduced thanks to a set of base abstractions I use internally in a custom MVI library (</em><em>ViewModel, </em><em>Reducer, </em><em>Middleware, etc.). These abstractions help streamline state handling, but the same principles can be applied manually without them.</em></blockquote><p>Our ViewModel only needs to define:</p><ul><li>The initial state</li><li>The reducer</li><li>Optional middlewares</li></ul><pre>@HiltViewModel<br>class ReviewViewModel @Inject constructor(<br>    reviewReducer: ReviewReducer,<br>) : ViewModel&lt;ReviewUiState&lt;String&gt;, ReviewEvent&gt;(<br>    initialState = ReviewUiState(item = EmptyItemUiState),<br>    reducer = reviewReducer,<br>    middlewares = setOf(submitReviewMiddleware())<br>) <br><br>private val EmptyItemUiState = ReviewItemUiState(<br>    itemId = &quot;3489&quot;,<br>    itemName = &quot;Cortego City Damesfiets Plus 28 Inch - 7 Versnellingen&quot;,<br>    shortDescription = &quot;Vanaf het moment dat je op de Cortego City damesfiets in mat-zwart stapt, voel je het verschil. Het verstelbare stuur en zadel zorgen voor een ergonomische zithouding.&quot;,<br>    imageUrl = &quot;https://www.fietsenplaats.nl/cdn/shop/files/Cortego-damesfiets-zwart-plus-1.jpg&quot;<br>)</pre><p>Notice how the ViewModel doesn’t contain any logic besides wiring everything together.</p><h4>Middleware: Handling Side Effects</h4><p>Side effects like network calls should be handled outside the reducer. That’s where Middleware comes in:</p><pre>fun submitReviewMiddleware() = Middleware&lt;ReviewUiState&lt;String&gt;, ReviewEvent, ReviewEvent.SubmitReview&gt; { intent -&gt;<br>    delay(2000) // simulate network delay<br>    dispatch(ReviewEvent.ReviewSubmitted)<br>}</pre><p>This function intercepts the SubmitReview intent, waits for 2 seconds, and dispatches a ReviewSubmitted intent back into the reducer.</p><h3>MVI vs MVVM: A Quick Comparison</h3><h4>State Management</h4><ul><li>MVVM: Spread across ViewModel and UI</li><li>MVI: Centralized in a single reducer</li></ul><h4>Predictability</h4><ul><li>MVVM: Can be hard to trace</li><li>MVI: All transitions go through a pure function</li></ul><h4>Testability</h4><ul><li>MVVM: Requires mocks and observers</li><li>MVI: Reducers and middleware can be unit tested easily</li></ul><h4>Learning Curve</h4><ul><li>MVVM: Beginner friendly</li><li>MVI: Steeper learning curve</li></ul><h3>Final Thoughts</h3><p>This implementation might feel a bit more verbose at first, but the clarity and consistency of MVI really pays off when your UI and state grow in complexity. With a clean separation of concerns, your state becomes much easier to reason about, debug, and test.</p><h3>What’s Next?</h3><p>In the next article, we’ll compare this custom MVI implementation with an existing framework like <strong>Orbit MVI</strong>, which provides additional tooling and structure on top of the same principles.</p><p>If you found this helpful, follow me for updates and feel free to leave a comment or suggestion below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b900f34fee8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing a Review Flow in Android using MVVM and Jetpack Compose]]></title>
            <link>https://medium.com/@matiasdelbel/implementing-a-review-flow-in-android-using-mvvm-and-jetpack-compose-fce217d138d5?source=rss-51e8f2d50f4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fce217d138d5</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[mvi]]></category>
            <dc:creator><![CDATA[Matías Del Bel]]></dc:creator>
            <pubDate>Wed, 23 Jul 2025 09:43:52 GMT</pubDate>
            <atom:updated>2025-07-23T09:43:52.914Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article series, we’re going to explore different architectural approaches to implement a modern review flow in Android. We’ll start with an implementation using the MVVM pattern.</p><p>Then, in the next articles, we’ll reimplement the same flow using two different MVI-style architectures. Finally, we’ll wrap things up with a comparison article, analyzing the trade-offs of each solution.</p><p>Let’s dive into the MVVM version.</p><blockquote>You can explore the full implementation of this MVVM-based review flow in the <a href="https://github.com/matiasdelbel/mvvm-form-feedback/tree/main">GitHub repository</a>.</blockquote><h4>The scenario</h4><p>Imagine we want to allow users to rate a product, write a description of their experience, and submit that review. The flow is composed of three screens:</p><ol><li><strong>Landing:</strong> Displays the product information.</li><li><strong>Rating: </strong>Users rate and describe their experience.</li><li><strong>Summary:</strong> Shows the review content before submission.</li></ol><h4>Navigation setup</h4><p>We use <strong>NavHost</strong> with a root route (<strong>ReviewRoute</strong>) and nested destinations. The <strong>ReviewViewModel</strong> is scoped to the root so all screens share the same state:</p><pre>fun NavGraphBuilder.review(navController: NavController) {<br>    navigation(<br>        route = ReviewRoute,<br>        startDestination = ReviewLandingRoute<br>    ) {<br>        reviewLanding(navController)<br>        reviewRating(navController)<br>        reviewSummary(navController)<br>    }<br>}</pre><p>Each screen retrieves the ViewModel from the parent backstack entry:</p><pre>val parentEntry = remember(entry) { navController.getBackStackEntry(route = ReviewRoute) }<br>val viewModel = hiltViewModel&lt;ReviewViewModel&gt;(parentEntry)<br>val state = viewModel.state.collectAsState().value</pre><h4>ViewModel &amp; state management</h4><p>The ReviewViewModel is the core of the architecture. It exposes a StateFlow with the current UI state:</p><pre><br>@HiltViewModel<br>class ReviewViewModel @Inject constructor(<br>    private val reviewValidator: ReviewValidator,<br>    private val submitReviewUseCase: SubmitReviewUseCase,<br>) : ViewModel() {<br><br>    private val _state = MutableStateFlow(ReviewUiState(item = ReviewItemMockUiState))<br>    val state: StateFlow&lt;ReviewUiState&gt; = _state.asStateFlow()<br>    <br>    fun onRatingSelected(rating: Int) { /*...*/ }<br>    fun onDescriptionChanged(description: String) { /*...*/ }<br>    fun submitReview() { /*...*/ }<br>}</pre><p>The state (ReviewUiState) contains product data, the review in progress, and possible validation errors.</p><h4>Input handling and validation</h4><p>Each time the user interacts with the UI (selects a rating or types a description), we update the review state and run validation:</p><pre>fun onRatingSelected(rating: Int) {<br>    val newReview = state.value.review?.copy(rating = rating) ?: ReviewRatingUiState(rating = rating)<br><br>    _state.value = state.value.copy(<br>        errors = reviewValidator.validate(newReview),<br>        review = newReview<br>    )<br>}</pre><p>Validation errors are represented as a ReviewError data class and injected into the UI:</p><pre>if (errors?.rating != null) {<br>    Text(<br>        text = stringResource(R.string.please_rate_the_product),<br>        color = MaterialTheme.colorScheme.error<br>    )<br>}</pre><h4>UI with Jetpack Compose</h4><p>We use composable functions for each screen. For example, the rating screen (ReviewRatingPane) displays a row of star buttons and a text field:</p><pre>Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly) {<br>    for (i in 1..state.maxRating) {<br>        StarButton(selected = state.rating &gt;= i, onClick = { onRatingSelected(i) })<br>    }<br>}<br><br>OutlinedTextField(<br>    value = state.description,<br>    onValueChange = onDescriptionChanged,<br>    label = { Text(&quot;Describe your experience&quot;) },<br>    supportingText = { /* error text here */ },<br>    minLines = 3,<br>    modifier = Modifier.fillMaxWidth()<br>)</pre><p>The “Next” button is only enabled when there are no validation errors:</p><pre>Button(<br>    onClick = onReviewFinished,<br>    enabled = errors == NoReviewError<br>) {<br>    Text(&quot;Next&quot;)<br>}</pre><h4>Submitting the review</h4><p>On the summary screen, the user can submit their review. When the button is clicked, we simulate an asynchronous call:</p><pre>fun submitReview() {<br>    viewModelScope.launch(Dispatchers.IO) {<br>        val syncingReview = state.value.review?.copy(synchronizing = true) ?: ReviewRatingUiState(synchronizing = true)<br>        _state.value = state.value.copy(review = syncingReview)<br><br>        submitReviewUseCase()<br><br>        _state.value = state.value.copy(review = syncingReview.copy(synchronizing = false))<br>    }<br>}</pre><p>This allows you to display a progress indicator during submission if needed.</p><h4>Final thoughts</h4><p>In this article, we walked through how to build a review flow using the MVVM pattern, leveraging StateFlow for reactive state handling and Jetpack Compose for UI rendering. We implemented real-time validation and a clean navigation setup using a shared ViewModel across multiple screens.</p><p>In the next article, we’ll implement the same review flow using an MVI architecture with a unidirectional data flow, and compare how responsibilities shift between components.</p><p>Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fce217d138d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVI vs MVVM in Android: A Balanced Take with Code Snippets]]></title>
            <link>https://medium.com/@matiasdelbel/mvi-vs-mvvm-in-android-a-balanced-take-with-code-snippets-f06d0385d653?source=rss-51e8f2d50f4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f06d0385d653</guid>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[mvi]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Matías Del Bel]]></dc:creator>
            <pubDate>Tue, 08 Jul 2025 13:58:34 GMT</pubDate>
            <atom:updated>2025-07-08T13:58:34.040Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of Android architecture patterns, <strong>MVVM</strong> has long been the de facto choice. But recently, <strong>MVI (Model-View-Intent)</strong> is gaining popularity for its functional, unidirectional approach to state management.</p><p>In this article, we’ll explore five <strong>advantages</strong> of MVI over MVVM — and to keep it balanced — we’ll immediately follow each with a <strong>disadvantage</strong>. Let’s dig in.</p><blockquote>🔗 If you’re new to MVI, you might want to check out <a href="https://medium.com/p/80d885456bf4">this previous post</a>, where I walk through a hands-on implementation of MVI in Jetpack Compose, with code samples and structure explained.</blockquote><h4>1. Predictable State Management</h4><p><strong>MVI offers a single source of truth — an immutable </strong><strong>UiState that represents the entire screen. </strong>This makes state transitions explicit and easier to follow.</p><pre>data class LoginState(<br>    val isLoading: Boolean = false,<br>    val error: String? = null,<br>    val isLoggedIn: Boolean = false<br>)</pre><p>All changes to the UI go through a reducer function:</p><pre>fun reduce(state: LoginState, intent: LoginIntent): LoginState = when (intent) {<br>    is LoginIntent.Submit -&gt; state.copy(isLoading = true, error = null)<br>    is LoginIntent.Success -&gt; state.copy(isLoading = false, isLoggedIn = true)<br>    is LoginIntent.Error -&gt; state.copy(isLoading = false, error = intent.message)<br>}</pre><p>This approach ensures no accidental UI state inconsistencies — every frame is a snapshot of truth.</p><h4>❌ Verbose Boilerplate</h4><p><strong>With this predictability comes extra boilerplate. </strong>You’ll need to define:</p><ul><li>An intent sealed class</li><li>A state data class</li><li>Reducers</li><li>Possibly middleware for side effects</li></ul><p>For simple screens, MVI can feel like you’re writing a novel just to toggle a button.</p><h4>2. Pure Functions = Better Testability</h4><p>The reducer is a <strong>pure function</strong>: given a state and an intent, it always returns the same result.</p><p>That makes testing easy:</p><pre>@Test<br>fun `submit intent sets loading to true`() {<br>    val initialState = LoginState()<br>    val newState = reduce(initialState, LoginIntent.Submit)<br>    assertTrue(newState.isLoading)<br>}</pre><p>No LiveData, no mocking, no surprises.</p><h4>❌ Steep Learning Curve</h4><p>If you’re coming from MVVM or imperative patterns, <strong>MVI can feel alien</strong>.<br> Terms like <em>reducers</em>, <em>effects</em>, and <em>unidirectional flow</em> may sound more Redux than Android.</p><p>Understanding how intents, reducers, state, and side effects interact takes time and often requires tooling support or custom abstractions.</p><h4>3. Time-Travel Debugging</h4><p>Because state is immutable and transitions are centralized, <strong>you can replay the entire state history</strong>, enabling time-travel debugging or undo functionality.</p><pre>val history = mutableListOf&lt;LoginState&gt;()<br><br>fun onIntent(intent: LoginIntent) {<br>    val newState = reduce(currentState, intent)<br>    history.add(newState)<br>    currentState = newState<br>}</pre><p>Great for dev tools, snapshots, and debugging bugs that are hard to reproduce.</p><h4>❌ State Explosion</h4><p><strong>You must represent everything in the state</strong>, even things like snackbars or navigation events.</p><p>That means adding non-persistent UI events into the state model:</p><pre>data class LoginState(<br>    val showSnackbar: String? = null,<br>    ...<br>)</pre><p>Or adding separate Effect channels. Either way, complexity builds up fast.</p><h4>4. Explicit User Interaction Modeling</h4><p>In MVI, every user interaction becomes an <strong>Intent</strong>, making the flow clear and easy to trace.</p><pre>sealed class LoginIntent {<br>    object Submit : LoginIntent()<br>    data class Error(val message: String) : LoginIntent()<br>    object Success : LoginIntent()<br>}</pre><p>Unlike MVVM, where business logic may be scattered across multiple observers, MVI makes it <strong>impossible to hide logic behind side effects</strong>.</p><h4>❌ Handling One-Time Events Is Harder</h4><p>Navigation, toast messages, or dialogs are <strong>transient UI events</strong>, and MVI’s immutable state model makes them difficult to handle cleanly.</p><p>You might need constructs like:</p><pre>sealed class LoginEffect {<br>    data class ShowToast(val msg: String) : LoginEffect()<br>    object NavigateToHome : LoginEffect()<br>}</pre><p>Then emit them through SharedFlow or channels, adding extra plumbing.</p><h4>5. Unidirectional Flow Is Easier to Reason About</h4><p>In MVI, the flow is always the same:</p><pre>Intent -&gt; Reducer -&gt; New State -&gt; Render</pre><p>This makes the mental model easier to reason about, especially in larger teams or codebases.</p><h4>❌ Overhead for Simple Use Cases</h4><p>If your screen is a basic form with one button and two inputs, MVI can feel like swatting a fly with a bazooka comparing to MVVM’s simplicity:</p><pre>fun onLoginClicked() {<br>    viewModelScope.launch {<br>        isLoading.value = true<br>        val result = loginUseCase(email.value, password.value)<br>        isLoading.value = false<br>        ...<br>    }<br>}</pre><p>Sometimes, the “best” architecture is the one with the least friction for the use case.</p><h3>Final Thoughts</h3><p>MVI shines in <strong>complex UI flows</strong>, where state consistency, testability, and debugging are paramount. But it comes with <strong>overhead and a learning curve</strong> that may not be worth it for every screen.</p><p>If you’re building <strong>scalable, long-term products</strong>, adopting MVI with the right tooling can pay off. But for fast prototyping or simple apps, MVVM may still offer the most efficient developer experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f06d0385d653" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a TODO App Using MVI and Jetpack Compose]]></title>
            <link>https://proandroiddev.com/building-a-todo-app-using-mvi-and-jetpack-compose-80d885456bf4?source=rss-51e8f2d50f4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/80d885456bf4</guid>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mvi]]></category>
            <category><![CDATA[compose]]></category>
            <dc:creator><![CDATA[Matías Del Bel]]></dc:creator>
            <pubDate>Tue, 01 Jul 2025 07:54:31 GMT</pubDate>
            <atom:updated>2025-07-28T14:28:30.052Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we’re going to explore how to implement the <strong>MVI (Model–View–Intent)</strong> in a Jetpack Compose Android app, using a hands-on example: a simple TODO list.</p><p>While the functionality of the app is intentionally minimal — adding, viewing, and deleting items — it serves as a clear foundation for understanding how MVI works in practice.</p><p>We’ll walk through:</p><ul><li>The structure of an MVI-based feature</li><li>How to model user actions as Intents</li><li>How to represent and manage the UiState</li><li>How to write a pure Reducer for state transitions</li><li>How to handle side effects using Middlewares</li><li>How to wire everything up in the ViewModel</li><li>And how the UI layer (the Pane) reacts to state and dispatches new actions</li></ul><p>Whether you’re new to MVI or looking to refine your architectural patterns in Compose apps, this guide will help you understand how to build a scalable, testable UI layer with <strong>unidirectional data flow</strong>.</p><p>Let’s dive in.</p><h3>Why MVI?</h3><p>MVI is a unidirectional architecture pattern that simplifies UI state management by enforcing a single source of truth and predictable state transitions. It’s particularly well-suited for modern Compose-based UIs because:</p><ul><li>It makes state mutations explicit.</li><li>Side effects are handled in a controlled and testable way.</li><li>The UI becomes a pure function of state.</li></ul><h3>Disclaimer: Class Naming</h3><p>For simplicity, this sample uses very <strong>generic class names</strong> like Intent, UiState, and Reducer. <strong>In a production app, it’s highly recommended to scope these to the feature, e.g., </strong><strong>TodoIntent, </strong><strong>TodoUiState, etc., to avoid confusion and improve readability when the codebase grows.</strong></p><h3>Project Structure</h3><p>Here’s a quick look at the feature structure used in the app:</p><pre>feature/<br> ├── Intent.kt         // User actions<br> ├── UiState.kt        // Current UI representation<br> ├── Reducer.kt        // Pure state transformation logic<br> ├── ViewModel.kt      // Coordinates everything<br> ├── Middlewares.kt    // Side effects (e.g. data fetching)<br> ├── Module.kt         // Dependency injection<br> ├── Navigation.kt     // Feature navigation<br> ├── Pane.kt           // UI Composable</pre><p>This structure promotes clear separation of concerns and keeps business logic decoupled from UI rendering.</p><h3>Intents</h3><p>The Intent sealed interface defines all possible user actions and system events that can trigger state changes.</p><pre>sealed interface Intent {<br>    data object LoadItems : Intent<br>    data class AddItem(val value: String) : Intent<br>    data class DeleteItem(val id: String) : Intent<br>}</pre><p>Each intent represents an explicit request to change the application state. For example:</p><ul><li>LoadItems is dispatched when the screen initializes.</li><li>AddItem when a new item is submitted.</li><li>DeleteItem when a user removes a task.</li></ul><blockquote><em>🔍 </em><strong><em>MVI vs MVVM — Key Distinction</em></strong></blockquote><blockquote><em>In </em><strong><em>MVVM</em></strong><em>, you typically expose a single method for each action (e.g. </em><em>addItem()), and that method might trigger both the side effect and the state update internally.</em></blockquote><blockquote><em>In </em><strong><em>MVI</em></strong><em>, by contrast, </em><strong><em>each “action” tends to be represented by multiple intents</em></strong><em>:</em></blockquote><blockquote>- One intent to <strong>initiate</strong> the action (AddItem)</blockquote><blockquote>- Others to <strong>handle its effects or results</strong>, like success or error (AddItemSuccess, AddItemError)</blockquote><blockquote><em>This makes the flow </em><strong><em>explicit, traceable, and testable</em></strong><em> — every state change or side effect is driven by a well-defined intent.</em></blockquote><h3>UiState</h3><p>The UiState data class holds all the information needed to render the screen.</p><pre>data class UiState(<br>    val isLoading: Boolean = false,<br>    val items: List&lt;PendingItem&gt; = emptyList(),<br>    val error: String? = null<br>)</pre><p>This ensures a <strong>single source of truth</strong> for the UI. Any composable just needs to observe this state to render correctly, reducing bugs and inconsistencies.</p><h3>Reducer</h3><p>The Reducer handles <strong>pure transformations</strong> from one state to another based on an incoming Intent.</p><pre>class Reducer : MviReducer&lt;Intent, UiState&gt; {<br>    override fun reduce(currentState: UiState, intent: Intent): UiState {<br>        return when (intent) {<br>            is Intent.LoadItems -&gt; currentState.copy(isLoading = true)<br>            is Intent.AddItem -&gt; currentState.copy(<br>                items = currentState.items + PendingItem(id = UUID.randomUUID().toString(), value = intent.value)<br>            )<br>            is Intent.DeleteItem -&gt; currentState.copy(<br>                items = currentState.items.filterNot { it.id == intent.id }<br>            )<br>        }<br>    }<br>}</pre><blockquote><em>One of the main benefits of using a </em><em>sealed interface with a </em><em>when expression is </em><strong><em>exhaustiveness</em></strong><em>. The compiler ensures that all possible </em><em>Intent types are handled.</em></blockquote><blockquote><em>If you introduce a new intent (e.g., </em><em>EditItem), the compiler will </em><strong><em>force you to update</em></strong><em> this reducer, reducing the risk of missing behavior or bugs.</em></blockquote><h3>Middlewares</h3><p>Middlewares are used to handle <strong>side effects</strong>, like data loading or interactions with repositories.</p><p>For example, a LoadItemsMiddleware can trigger Intent.LoadItems and then dispatch a new intent once data is retrieved:</p><pre>class LoadItemsMiddleware(<br>    private val repository: PendingRepository<br>) : Middleware&lt;Intent, UiState&gt; {<br>   <br> override suspend fun process(<br>    intent: Intent,<br>    state: UiState,<br>    dispatch: Dispatch&lt;Intent&gt;<br> ) {<br>     if (intent is Intent.LoadItems) {<br>     val result = repository.getPendingItems()<br>     result.onSuccess { items -&gt;<br>       dispatch(intent = InternalIntent.LoadItemsSuccess(items))<br>     }.onFailure {<br>       dispatch(intent =InternalIntent.LoadItemsError(it.message)<br>     }<br>   }<br>}</pre><h3>ViewModel</h3><blockquote><strong>Disclaimer:</strong> I’m aware that using a ViewModel might seem unnecessary in this context, especially from a pure MVI perspective. In this case, I used it solely because I needed a lifecycle-aware class, and ViewModel was the most straightforward and lightweight solution for the job. The focus of this article is on showcasing the intent-reducer-effect flow, not enforcing architectural orthodoxy.</blockquote><p>The ViewModel is where the reducer and middleware come together. It receives intents, runs them through middleware, applies reducers, and exposes the final state to the UI.</p><pre>class TodoViewModel @Inject constructor(<br>    reducer: Reducer,<br>    middlewares: Set&lt;@JvmSuppressWildcards Middleware&lt;Intent, UiState&gt;&gt;<br>) : MviViewModel&lt;Intent, UiState&gt;(<br>    initialState = UiState(),<br>    reducer = reducer,<br>    middlewares = middlewares<br>)</pre><h3>Pane (Composable UI)</h3><p>Finally, the Pane is the screen itself. It reacts to UiState changes and sends user actions as Intents:</p><pre>@Composable<br>fun TodoPane(<br>    state: UiState,<br>    onTextChanged: (String) -&gt; Unit,<br>    onAddClicked: () -&gt; Unit,<br>    onDeleteClicked: (TodoItem) -&gt; Unit,<br>    modifier: Modifier = Modifier<br>) { }</pre><h3>Try It Yourself</h3><p>The full code is available here: 🔗 <a href="https://github.com/matiasdelbel/ui-mvi">https://github.com/matiasdelbel/ui-mvi</a></p><h3>Wrap-up</h3><p>Using MVI in Android Compose apps leads to predictable, testable, and scalable UI architecture. Even a simple TODO app benefits from the discipline of unidirectional data flow and clean separation of logic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80d885456bf4" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/building-a-todo-app-using-mvi-and-jetpack-compose-80d885456bf4">Building a TODO App Using MVI and Jetpack Compose</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[Automating screens verification with Roborazzi and GitHub Actions]]></title>
            <link>https://medium.com/@matiasdelbel/automating-screens-verification-with-roborazzi-and-github-actions-473b3301a5c0?source=rss-51e8f2d50f4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/473b3301a5c0</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[roborazzi]]></category>
            <category><![CDATA[screenshot-testing]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Matías Del Bel]]></dc:creator>
            <pubDate>Tue, 24 Jun 2025 11:10:05 GMT</pubDate>
            <atom:updated>2025-06-24T11:10:05.369Z</atom:updated>
            <content:encoded><![CDATA[<p>In modern Android development with Jetpack Compose, @Preview functions are more than just design-time helpers—they can also be leveraged for validating UI consistency through automated visual regression tests.</p><p>In this post, I’ll walk you through how I automated screenshot verification using <a href="https://github.com/takahirom/roborazzi">Roborazzi</a> and GitHub Actions. This builds on a <a href="https://medium.com/@matiasdelbel/building-a-clean-multi-step-form-in-jetpack-compose-a-deep-dive-03c4447d723d">previous project</a> where I implemented a credit card form in Compose. I wanted to add screenshot tests without writing too much boilerplate, and this is the solution I landed on.</p><h3>The Goal</h3><p>Validate that the UI haven’t changed unexpectedly. If they have, automatically update the screenshots and commit them directly to the branch—no manual steps involved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6_psocvuySnI8pxY8Dopvw.png" /><figcaption>Screenshots added to the project</figcaption></figure><p>Here’s how the workflow works:</p><ol><li><strong>Running </strong><strong>verifyAndRecordRoborazzi</strong> to validate or generate screenshots.</li><li><strong>Checking for changes</strong> in the app/screenshots directory.</li><li><strong>If screenshots differ</strong>, committing those changes to the branch.</li><li><strong>Add a comment to the PR </strong>noting that screenshots were updated.</li></ol><h3>Setting Up Roborazzi</h3><p>First, apply the Roborazzi plugin in your project:</p><pre>plugins {<br>    alias(libs.plugins.roborazzi)<br>}</pre><p>Configure it in your build.gradle.kts:</p><pre>roborazzi {<br>    @OptIn(ExperimentalRoborazziApi::class)<br>    generateComposePreviewRobolectricTests {<br>        enable = true<br>        includePrivatePreviews = false<br>        packages = listOf(&quot;com.matiasdelbel.multistepform.ui&quot;)<br>    }<br>    outputDir.set(file(&quot;screenshots&quot;))<br>}</pre><p>Add the required dependencies:</p><pre>dependencies {<br>    testImplementation(libs.preview.scanner.compose)<br>    testImplementation(libs.preview.scanner.roborazzi)<br>    testImplementation(libs.robolectric)<br>}</pre><h3>GitHub Actions Workflow</h3><p>Here’s an extract of the GitHub Actions workflow used to automate screenshot verification and updates:</p><pre>name: Verify screenshots</pre><pre>on:<br>  pull_request:<br>    types: [opened, synchronize]</pre><pre>jobs:<br>  verify-screenshots:<br>    runs-on: ubuntu-latest</pre><pre>    steps:</pre><pre>      - name: Run verify and record screenshots<br>        run: ./gradlew verifyAndRecordRoborazziDebug</pre><pre>      - name: Commit and push screenshots if changed<br>        id: commit_screenshots<br>        if: failure()<br>        run: |<br>          git config --global user.name &quot;github-actions[bot]&quot;<br>          git config --global user.email &quot;github-actions[bot]@users.noreply.github.com&quot;<br>          if [ -n &quot;$(git status --porcelain app/screenshots)&quot; ]; then<br>            git add app/screenshots<br>            git commit -m &quot;🤖 Updated Roborazzi screenshots after verification&quot;<br>            git push origin HEAD:${{ github.head_ref }}<br>            echo &quot;changed=true&quot; &gt;&gt; $GITHUB_OUTPUT<br>          else<br>            echo &quot;No screenshot changes detected.&quot;<br>            echo &quot;changed=false&quot; &gt;&gt; $GITHUB_OUTPUT<br>          fi</pre><pre>      - name: Comment on PR if screenshots were updated<br>        if: steps.commit_screenshots.outputs.changed == &#39;true&#39;<br>        uses: actions/github-script@v7<br>        with:<br>          script: |<br>            github.rest.issues.createComment({<br>              issue_number: context.issue.number,<br>              owner: context.repo.owner,<br>              repo: context.repo.repo,<br>              body: &quot;Roborazzi screenshots have been updated and committed automatically to this PR branch. Please review the visual changes.&quot;<br>            })</pre><blockquote>🔍 <a href="https://github.com/matiasdelbel/multi-step-form/pull/1">You can view the full PR here</a></blockquote><h3>Pros of Using Previews for Screenshot Tests</h3><ul><li><strong>Instant visual feedback</strong> for UI changes.</li><li><strong>Easy to integrate</strong> into CI/CD pipelines like GitHub Actions.</li><li><strong>Perfect for catching unintended design regressions.</strong></li><li><strong>Lightweight alternative</strong> to full-blown E2E tests for UI components.</li></ul><h3>Downsides &amp; Trade-offs</h3><ul><li><strong>Noise from expected UI changes</strong> can lead to redundant commits.</li><li><strong>Limited to static visual validation</strong> — no user interaction or navigation.</li><li><strong>Preview rendering can be slow</strong> in large codebases.</li><li><strong>Not all previews should be part of visual tests</strong> (more on that below).</li></ul><h3>What About Previews Not Meant for Screenshot Testing?</h3><p>Not every @Preview in your codebase should be included in visual tests. For example, some might be experimental, internal-only, or just visual scaffolding.</p><p>To exclude these, Roborazzi offers:</p><pre>includePrivatePreviews = false</pre><p>This skips any preview that’s either non-public or not intended for test verification.</p><blockquote><em>💡 </em><strong>Alternative approach:</strong> You can also control inclusion using specific packages, composableNames, or by tagging previews with custom annotations.</blockquote><h3>What Projects Benefit Most from this?</h3><p>This solution is especially effective in:</p><ul><li><strong>UI libraries or design systems</strong>, where each component already has previews.</li><li><strong>Apps with strong visual identity</strong> and design consistency requirements.</li><li><strong>Teams with limited bandwidth</strong> for maintaining end-to-end tests.</li></ul><p>On the flip side, it’s <em>less</em> ideal for:</p><ul><li>Highly dynamic UIs.</li><li>UIs heavily dependent on runtime data.</li><li>Screens with complex user flows.</li></ul><h3>Looking Ahead: Google’s Alternative</h3><p>Google is also working on a <strong>preview-based screenshot testing library</strong>, currently in <strong>alpha</strong>. It aims to bring a more integrated solution to Compose visual testing in the future.</p><p>🔗 <a href="https://developer.android.com/studio/preview/compose-screenshot-testing">Read more about it here</a></p><blockquote><em>⚠️ </em>Until it matures, Roborazzi remains the most robust and flexible option for Compose screenshot testing in CI.</blockquote><h3>Final Thoughts</h3><p>If you’re already using Compose previews in your day-to-day development, this setup lets you <strong>turn them into visual regression tests</strong> — with minimal effort.</p><p>By integrating Roborazzi and GitHub Actions, you get a clean, automated workflow that gives you visual confidence in your UI and catches design regressions before they hit production.</p><p>💬 Have you tried using Compose previews for testing? Drop a comment — I’d love to hear how you’re handling UI verification in Compose.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=473b3301a5c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Clean Multi-Step Form in Jetpack Compose — A Deep Dive]]></title>
            <link>https://medium.com/@matiasdelbel/building-a-clean-multi-step-form-in-jetpack-compose-a-deep-dive-03c4447d723d?source=rss-51e8f2d50f4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/03c4447d723d</guid>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flow]]></category>
            <dc:creator><![CDATA[Matías Del Bel]]></dc:creator>
            <pubDate>Tue, 17 Jun 2025 14:28:20 GMT</pubDate>
            <atom:updated>2025-06-17T14:28:51.369Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Clean Multi-Step Form in Jetpack Compose — A Deep Dive</h3><p>Handling multi-step user input flows — such as checkout forms, onboarding, or surveys — is a common challenge in mobile development. It’s easy to end up with tangled UI logic, brittle state handling, or forms that are difficult to extend.</p><p>In this article, I’ll share a clean and scalable solution using <strong>Jetpack Compose</strong>, <strong>StateFlow</strong>, and modern Android architecture patterns — all wrapped up in a working sample app.</p><p>👉 <a href="https://github.com/matiasdelbel/multi-step-form">Check out the code on GitHub</a></p><h3>The Problem</h3><p>Multi-step forms are deceptively complex:</p><ul><li>State must persist across steps</li><li>Validation logic can get messy</li><li>Navigation (forward/back) must be predictable</li><li>Code reuse and testing often get sidelined</li></ul><p>Compose simplifies UI development, but it also forces us to rethink how we structure logic and state. That’s where this architecture shines.</p><h3>Project Goals</h3><p>I wanted to build a multi-step form that is:</p><ul><li><strong>Composable</strong> — Each screen is self-contained.</li><li><strong>Clean</strong> — With clear separation of UI, state, and logic.</li><li><strong>Scalable</strong> — Easy to extend with more fields or steps.</li><li><strong>Modern</strong> — Using 2025-era Android best practices.</li></ul><h3>Tech Stack &amp; Patterns</h3><ul><li><strong>UI —</strong> Jetpack Compose</li><li><strong>State Management</strong> — ViewModel + StateFlow</li><li><strong>Navigation</strong> — Navigation Compose</li><li><strong>DI</strong> — Hilt</li><li><strong>Validation</strong> — Modular use-cases</li><li><strong>CI/CD </strong>— GitHub Actions</li></ul><h3>Architecture Overview</h3><p>The overall flow looks like this:</p><pre>NavHost --&gt; ViewModels --&gt; StateFlow --&gt; Validators --&gt; Screens</pre><ul><li><strong>NavHost</strong> manages screen flow</li></ul><pre>NavHost(<br>        navController = navController,<br>        modifier = modifier.padding(insets),<br>        startDestination = CardFormRoute.CreditCardGraph<br>) { cardForm(navController = navController) }</pre><ul><li><strong>ViewModel</strong> holds a single CardFormState object (data class)</li><li><strong>StateFlow</strong> exposes the state reactively</li></ul><pre><br>@HiltViewModel<br>class CardFormViewModel @Inject constructor(<br>    private val cardNumberValidator: CardNumberValidator,<br>    // Other properties ...<br>) : ViewModel() {<br><br>    private val _state = MutableStateFlow(value = CardFormState())<br>    val state: StateFlow&lt;CardFormState&gt; = _state<br><br>    fun onCardNumberChanged(newNumber: String) {<br>        _state.value = _state.value.copy(<br>            cardNumber = InputFieldValue(<br>                value = newNumber,<br>                error = cardNumberValidator.validate(newNumber)<br>            ),<br>            cardType = detectCardType(newNumber)<br>        )<br>    }<br>    <br>    // Other functions ... <br>}</pre><ul><li><strong>Use Cases</strong> handle validation logic</li></ul><pre>class CardNumberValidator @Inject constructor() {<br><br>    fun validate(number: String): CardNumberError? = when {<br>        number.isBlank() -&gt; CardNumberError.Empty<br>        !isValidLuhn(number) -&gt; CardNumberError.InvalidLuhn<br>        else -&gt; null<br>    }<br>}</pre><ul><li><strong>Screens</strong> consume state and respond to changes declaratively</li></ul><pre>@Composable<br>fun CardNumberPane(<br>    number: InputFieldValue&lt;CardNumberError&gt;,<br>    mask: String,<br>    onCardNumberChange: (newNumber: String) -&gt; Unit,<br>    onNext: () -&gt; Unit,<br>    modifier: Modifier = Modifier,<br>)</pre><h3>Extending the Flow</h3><p>Need to add a new step?</p><ol><li>Add a new Composable (e.g. CardHolderPane)</li><li>Extend your CardFormState data class</li><li>Plug into navigation via NavHost</li><li>Add new validation logic (if needed)</li></ol><p>Thanks to clear modularity, new steps don’t impact unrelated code.</p><h3>Testing &amp; Reuse</h3><p>The architecture favors unit testing and code reuse. For example:</p><ul><li>Validators are pure functions or small classes</li><li>FormState updates are predictable and testable</li><li>Screens are isolated and preview-friendly</li></ul><p>You can easily migrate this to support things like:</p><ul><li>Draft saving</li><li>Remote validation (e.g. email availability)</li><li>Multi-platform support (e.g. Compose Multiplatform)</li></ul><h3>Key Takeaways</h3><ul><li>Compose works best with a clean, reactive state model.</li><li>StateFlow makes it easy to keep UI in sync with logic.</li><li>Modular validation + declarative UI = maintainable code.</li><li>Clean navigation flows lead to better UX and testability.</li></ul><h3>Final Thoughts</h3><p>Multi-step forms don’t need to be messy. With Compose and a bit of structure, you can build beautiful, robust flows that scale.</p><p>Whether you’re building onboarding, checkouts, or dynamic forms — this architecture can serve as a foundation.</p><p>👋 Questions, feedback, or ideas? Drop them in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03c4447d723d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Disposables and View Models]]></title>
            <link>https://medium.com/@matiasdelbel/disposables-and-view-models-56d193441369?source=rss-51e8f2d50f4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/56d193441369</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[extension-functions]]></category>
            <category><![CDATA[rxandroid]]></category>
            <dc:creator><![CDATA[Matías Del Bel]]></dc:creator>
            <pubDate>Mon, 19 Oct 2020 21:03:45 GMT</pubDate>
            <atom:updated>2020-10-19T21:03:45.600Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to avoid boilerplate code and keep your view models clean</h4><p>One nice thing about using JetPack Components and Coroutines is that the creation of scopes and its lifecycles are being handled by the JetPack Component out of the box. This allows us to use the viewModelScope associated with the view models without caring about the clean up when the view model is no longer used.</p><p>Unfortunately, we don’t have this type of integration between JetPack Components and RxJava. For Rx, we are responsible to clean the Disposable when the View Model is not used anymore. This can lead us to write a lot of boilerplate code or create awkward inheritances.</p><p>Let say we have an <strong>ExampleViewModel </strong>that consumes two different use cases. The use cases return they result as Rx flows:</p><pre>class ExampleViewModel(<br>  private val anUseCase: UseCase, <br>  private val anotherUseCase: OtherUseCase<br>): ViewModel() {</pre><pre>  private val disposable = CompositeDisposable()<br> <br>  fun executeAnUseCase() = disposable.add( <br>     anUseCase<br>        .invoke()<br>        .subscribe { handleAnUseCaseResult() }<br>  )}</pre><pre>  fun executeAnotherUseCase() = disposable.add( <br>     anotherUseCase<br>        .invoke()<br>        .subscribe { handleAnotherUseCaseResult() }<br>  )}</pre><pre>  override fun onCleared() {<br>     disposable.clear()<br>     super.onCleared()<br>  }<br>}</pre><p>Like we mentioned before, we are in charge of disposing of the flows. This code can be improved using a similar approach that the view models use with coroutine scopes. For that, we will need to create some extension functions and properties following the approach that already commented on in this article:</p><p><a href="https://medium.com/@matiasdelbel/where-to-put-extension-functions-69a5148a7439">Where to put extension functions?</a></p><p>We will create a viewModelDisposable extension property that will be stored in the view model tags. And when the operating system calls onCleared on the view model, we will clear also the disposable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b9a1bf2966682404d6a97da01ec0905/href">https://medium.com/media/0b9a1bf2966682404d6a97da01ec0905/href</a></iframe><p>This way we can remove some code from our <strong>ExampleViewModel:</strong></p><pre>class ExampleViewModel(<br>  private val anUseCase: UseCase, <br>  private val anotherUseCase: UseCase<br>): ViewModel {<br> <br>  fun executeAnUseCase() = anUseCase()<br>    .subscribe { handleAnUseCaseResult() }<br>    .composeInto(<em>viewModelDisposable)<br></em>  }<br>  <br>  fun executeAnotherUseCase() = anUseCase()<br>    .subscribe { handleAnotherUseCaseResult() }<br>    .composeInto(<em>viewModelDisposable)</em><br>  }<br>}</pre><p>As you can see, we the help of some extension functions we can write a more readable code without the need to create our custom inheritances.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56d193441369" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>