<?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 Ignacio Cabanas on Medium]]></title>
        <description><![CDATA[Stories by Ignacio Cabanas on Medium]]></description>
        <link>https://medium.com/@cabanas.ignacio?source=rss-667f6151b7d5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*C0mTx3Ufw5h7LSv8qSb3ng.jpeg</url>
            <title>Stories by Ignacio Cabanas on Medium</title>
            <link>https://medium.com/@cabanas.ignacio?source=rss-667f6151b7d5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 08:19:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cabanas.ignacio/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[Kotlin Coroutines vs RxJava: When to Choose What in 2025]]></title>
            <link>https://medium.com/@cabanas.ignacio/kotlin-coroutines-vs-rxjava-when-to-choose-what-in-2025-728d1759980c?source=rss-667f6151b7d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/728d1759980c</guid>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[coroutines-in-kotlin]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Ignacio Cabanas]]></dc:creator>
            <pubDate>Mon, 30 Jun 2025 12:36:26 GMT</pubDate>
            <atom:updated>2025-06-30T12:36:26.821Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*JaoYn27i2Y9o1to1.png" /></figure><p>Both Kotlin Coroutines and RxJava are mature, production-ready solutions for Android async programming. The question isn’t which is “better” — it’s which fits your specific context.</p><h3>The Current Landscape</h3><p><strong>RxJava 3.x</strong> is stable and battle-tested with a rich operator ecosystem. It excels at complex reactive patterns and stream processing. Major companies continue using it for sophisticated data pipelines.</p><p><strong>Kotlin Coroutines</strong> have become Android’s default async solution. Google’s official libraries assume Coroutines, from Jetpack Compose to Room. The syntax is cleaner and integrates seamlessly with Kotlin language features.</p><p>Performance is comparable between both. Coroutines have slight memory advantages for simple operations, while RxJava’s optimized operators can outperform naive Coroutine implementations in complex scenarios.</p><p>New projects predominantly choose Coroutines, while established RxJava codebases continue successfully.</p><h3>Head-to-Head: Where It Really Matters</h3><h4>Learning Curve and Team Onboarding</h4><p><strong>RxJava’s Challenge</strong>: New developers often struggle with the marble diagram mental model. Concepts like hot vs cold observables, subscription management, and operator composition require significant upfront investment. I’ve seen junior developers take 2–3 months to become productive with RxJava.</p><pre>// RxJava - requires understanding of observables, operators, and subscription lifecycle<br>userRepository.getUser(userId)<br>    .subscribeOn(Schedulers.io())<br>    .flatMap { user -&gt; <br>        profileRepository.getProfile(user.id)<br>            .map { profile -&gt; UserWithProfile(user, profile) }<br>    }<br>    .observeOn(AndroidSchedulers.mainThread())<br>    .subscribe(<br>        { result -&gt; updateUI(result) },<br>        { error -&gt; handleError(error) }<br>    )</pre><p><strong>Coroutines’ Advantage</strong>: The sequential nature feels natural to developers coming from synchronous backgrounds. Suspend functions read like regular functions, making onboarding smoother.</p><pre>// Coroutines - reads like synchronous code<br>viewModelScope.launch {<br>    try {<br>        val user = withContext(Dispatchers.IO) { userRepository.getUser(userId) }<br>        val profile = withContext(Dispatchers.IO) { profileRepository.getProfile(user.id) }<br>        updateUI(UserWithProfile(user, profile))<br>    } catch (error: Exception) {<br>        handleError(error)<br>    }<br>}</pre><p><strong>Winner</strong>: Coroutines for team velocity, especially with mixed experience levels.</p><h4>Error Handling and Recovery</h4><p><strong>RxJava’s Strength</strong>: Sophisticated error operators like retry(), retryWhen(), and onErrorResumeNext() provide granular control over failure scenarios.</p><pre>networkCall()<br>    .retryWhen { errors -&gt;<br>        errors.take(3).delay(1, TimeUnit.SECONDS)<br>    }<br>    .onErrorResumeNext { fallbackCall() }<br>    .subscribe(...)</pre><p><strong>Coroutines’ Approach</strong>: Traditional try-catch with some functional helpers. While simpler, it requires more manual work for complex retry logic.</p><pre>suspend fun fetchWithRetry(): Result {<br>    repeat(3) { attempt -&gt;<br>        try {<br>            return networkCall()<br>        } catch (e: Exception) {<br>            if (attempt == 2) throw e<br>            delay(1000)<br>        }<br>    }<br>}</pre><p><strong>Winner</strong>: RxJava for complex error handling scenarios, Coroutines for straightforward cases.</p><h4>Testing and Debugging</h4><p><strong>Coroutines’ Advantage</strong>: Testing feels natural with runTest and TestDispatcher. Debugging with breakpoints works as expected since it&#39;s not callback-based.</p><pre>@Test<br>fun `test user loading`() = runTest {<br>    val result = repository.loadUser(123)<br>    assertEquals(expectedUser, result)<br>}</pre><p><strong>RxJava’s Challenge</strong>: TestScheduler setup, marble testing, and debugging callback chains can be cumbersome. However, once mastered, RxJava’s testing tools are comprehensive.</p><p><strong>Winner</strong>: Coroutines for simplicity, RxJava for sophisticated testing scenarios.</p><h4>Complex Stream Operations</h4><p><strong>RxJava’s Domain</strong>: When you need to combine multiple data streams, handle backpressure, or implement complex windowing operations, RxJava shines.</p><pre>Observable.combineLatest(<br>    searchQuery.debounce(300, TimeUnit.MILLISECONDS),<br>    filterOptions.distinctUntilChanged(),<br>    sortOptions.distinctUntilChanged()<br>) { query, filters, sort -&gt;<br>    SearchParams(query, filters, sort)<br>}.switchMap { params -&gt;<br>    searchRepository.search(params)<br>}.subscribe(...)</pre><p><strong>Coroutines’ Limitation</strong>: While Flow provides many operators, complex stream compositions often require more boilerplate or custom operators.</p><p><strong>Winner</strong>: RxJava for reactive streams, Coroutines for straightforward async operations.</p><h3>Choose Coroutines When:</h3><ul><li><strong>New projects</strong> starting from scratch</li><li><strong>Kotlin-first teams</strong> who value language integration</li><li><strong>Simple to moderate async needs</strong> (API calls, database operations, UI updates)</li><li><strong>Team has limited reactive programming experience</strong></li><li><strong>Tight integration with Jetpack libraries</strong> (Compose, ViewModel, Room)</li></ul><h3>Stick with RxJava When:</h3><ul><li><strong>Existing RxJava codebase</strong> with significant investment</li><li><strong>Complex reactive patterns</strong> are core to your application</li><li><strong>Team expertise</strong> is heavily RxJava-focused</li><li><strong>Heavy stream processing</strong> requirements (real-time data, complex transformations)</li><li><strong>Need battle-tested solutions</strong> for edge cases</li></ul><h3>Hybrid Approach:</h3><p>Many successful teams use both. Coroutines for straightforward async work, RxJava for complex reactive scenarios. The key is establishing clear boundaries and team guidelines.</p><h3>Migration Strategies</h3><p>If you’re moving from RxJava to Coroutines:</p><ol><li><strong>Start with new features</strong> using Coroutines</li><li><strong>Convert simple chains first</strong> (single API calls, basic transformations)</li><li><strong>Leave complex reactive logic</strong> in RxJava until you have Coroutines expertise</li><li><strong>Use interop libraries</strong> like kotlinx-coroutines-rx2 during transition</li><li><strong>Migrate gradually</strong> — don’t attempt a big-bang rewrite</li></ol><p>Common migration pitfalls:</p><ul><li>Converting everything at once without understanding Coroutines deeply</li><li>Losing RxJava’s sophisticated error handling without replacement</li><li>Not considering performance implications of different patterns</li></ul><h3>Looking Forward</h3><p>Both technologies continue evolving. Coroutines are getting more reactive features (SharedFlow improvements, better backpressure), while RxJava 3.x focuses on stability and performance. The choice isn’t permanent — teams can and do evolve their approaches as needs change.</p><p><strong>Bottom line</strong>: In 2025, choose based on your team’s context, not industry hype. Coroutines offer simplicity and great language integration. RxJava provides sophisticated reactive programming tools. Both are excellent choices when used appropriately.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=728d1759980c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reactive State in Jetpack Compose: Leveraging remember, mutableStateOf, and rememberSaveable]]></title>
            <link>https://medium.com/@cabanas.ignacio/reactive-state-in-jetpack-compose-leveraging-remember-mutablestateof-and-remembersaveable-4fce67d689df?source=rss-667f6151b7d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fce67d689df</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[jetpack-compose-state]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Ignacio Cabanas]]></dc:creator>
            <pubDate>Fri, 08 Nov 2024 12:28:12 GMT</pubDate>
            <atom:updated>2024-11-08T12:29:49.395Z</atom:updated>
            <content:encoded><![CDATA[<p>Managing UI state effectively is essential for creating responsive and interactive applications in Jetpack Compose. Unlike the traditional XML-based approach, Jetpack Compose offers a unique set of tools designed specifically for declarative UI, making state management easier and more reactive. In this article, we’ll explore the key components for managing state in Jetpack Compose — remember, mutableStateOf, and rememberSaveable—and provide guidance on when and how to use each.</p><h3>Understanding State in Jetpack Compose</h3><p>In Jetpack Compose, the UI is built by describing how the interface should look based on the current state. When the state changes, the UI automatically re-composes to reflect those changes. This reactive nature means that managing state in Compose differs from the imperative approach used in traditional Android development.</p><h4>Why State Management Matters</h4><p>State management in Compose is crucial because:</p><ul><li>It drives the reactive nature of UI updates.</li><li>Proper state handling avoids unnecessary recompositions, improving app performance.</li><li>It makes UI components predictable and consistent with the underlying data.</li></ul><h3>Key Components for State Management</h3><p>Let’s explore the core tools provided by Jetpack Compose for managing state:</p><h4>remember</h4><p>The remember function in Compose stores a single object in memory during the recompositions of a composable function. This is useful for retaining state between recompositions while the composable function remains in memory.</p><p><strong>Example:</strong></p><pre>@Composable<br>fun Counter() {<br>    var count by remember { mutableStateOf(0) }<br>    Button(onClick = { count++ }) {<br>        Text(&quot;Count: $count&quot;)<br>    }<br>}</pre><p>In this example:</p><ul><li>remember is used to keep count across recompositions.</li><li>mutableStateOf allows the state to be mutable and observable, triggering UI updates whenever count changes.</li></ul><p><strong>When to Use </strong><strong>remember</strong>:</p><ul><li>For transient state that doesn’t need to persist across configuration changes (like screen rotations).</li><li>When storing UI-related states such as animation progress or temporary form inputs.</li></ul><h4>Limitations of remember:</h4><ul><li>It doesn’t retain state through configuration changes (e.g., rotating the screen).</li><li>Suitable only for temporary state that doesn’t need to be restored when the app returns to the foreground.</li></ul><h4>mutableStateOf</h4><p>mutableStateOf is used to create observable properties within composables. It enables the Compose runtime to detect changes to variables, triggering a UI recomposition when the value changes.</p><h4>Example:</h4><pre>var username by mutableStateOf(&quot;&quot;)</pre><p>In practice, mutableStateOf is often paired with remember or rememberSaveable to handle mutable state within composable functions.</p><p><strong>When to Use </strong><strong>mutableStateOf</strong>:</p><ul><li>When creating a mutable property that should trigger recompositions.</li><li>For properties within composables that need reactive updates.</li></ul><h4>Limitation of mutableStateOf:</h4><ul><li>It requires remember or rememberSaveable to avoid resetting on recompositions.</li></ul><h4>rememberSaveable</h4><p>rememberSaveable works similarly to remember, but it adds automatic state saving and restoration, making it resilient to configuration changes. This is particularly helpful for preserving state like text inputs across screen rotations.</p><h4>Example:</h4><pre>@Composable<br>fun UserInputField() {<br>    var text by rememberSaveable { mutableStateOf(&quot;&quot;) }<br>    TextField(value = text, onValueChange = { text = it })<br>}</pre><p>In this example:</p><ul><li>rememberSaveable retains the text value even if the screen rotates or the app is briefly backgrounded.</li><li>It’s ideal for states that represent persistent user input or UI state that should survive configuration changes.</li></ul><p><strong>When to Use </strong><strong>rememberSaveable</strong>:</p><ul><li>For UI state that needs to be retained across configuration changes.</li><li>When handling user input fields or values that users expect to persist during temporary app interruptions.</li></ul><h3>Choosing Between remember, mutableStateOf, and rememberSaveable</h3><p>Here’s a quick summary of when to use each:</p><p>remember</p><ul><li>Keeps state within the current composition scope</li><li>Temporary UI states that don’t need persistence</li></ul><p>mutableStateOf</p><ul><li>Creates observable properties for reactive UI updates</li><li>Making properties reactive within composable functions</li></ul><p>rememberSaveable</p><ul><li>Retains state across configuration changes and process death</li><li>Persistent user input, fields, or state that shouldn’t reset</li></ul><h3>Example Comparison</h3><p>Consider an app that allows a user to input text and increase a counter. We’ll use each tool appropriately to demonstrate the differences:</p><h4>Using remember with mutableStateOf for Transient Counter</h4><pre>@Composable<br>fun TransientCounter() {<br>    var count by remember { mutableStateOf(0) }<br>    Button(onClick = { count++ }) {<br>        Text(&quot;Count: $count&quot;)<br>    }<br>}</pre><p>This counter will reset on screen rotation since it’s managed only with remember and isn’t meant to persist.</p><h4>Using rememberSaveable for Persistent User Input</h4><pre>@Composable<br>fun PersistentUserInput() {<br>    var text by rememberSaveable { mutableStateOf(&quot;&quot;) }<br>    TextField(value = text, onValueChange = { text = it })<br>}</pre><p>In this example, the text input will persist across screen rotations, making it ideal for fields where users might enter significant information.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fce67d689df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enum vs Sealed Class in Kotlin: Which One Should You Use?]]></title>
            <link>https://medium.com/@cabanas.ignacio/enum-vs-sealed-class-in-kotlin-which-one-should-you-use-93920d2e4e8e?source=rss-667f6151b7d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/93920d2e4e8e</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[sealed-classes]]></category>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Ignacio Cabanas]]></dc:creator>
            <pubDate>Thu, 07 Nov 2024 12:06:21 GMT</pubDate>
            <atom:updated>2024-11-07T12:06:21.349Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*aOjnaZl1Wlicn7Ca2DGWlA.png" /></figure><p>In Kotlin, both enum and sealed classes allow developers to work with a fixed set of values or types, making them ideal for defining restricted data sets. However, there are key differences between the two that influence when and how they should be used. In this article, we’ll explore these differences, examine the strengths and limitations of each, and provide usage examples to help you decide when to choose a sealed class versus an enum class.</p><h3>Enum Classes</h3><p>An enum class is a data type that represents a fixed set of constants, each of which is represented by an instance of the enum class itself. Enums are a powerful tool when you need a predefined set of values, like the days of the week or traffic light colors.</p><p><strong>Example:</strong></p><pre>enum class TrafficLight {<br>    RED, YELLOW, GREEN<br>}</pre><h4>When to Use Enum Classes</h4><p>Use an enum class when:</p><ul><li>You need a fixed set of constants.</li><li>The values don’t require additional properties or complex behavior.</li><li>You want a simple representation of discrete, unchanging values.</li></ul><p><strong>Example Scenario</strong>: Representing days of the week or traffic lights (as in the example above) is straightforward with enums.</p><h4>Limitations of Enum Classes</h4><ul><li>Enum classes in Kotlin <strong>don’t support inheritance</strong>, so you cannot create a subclass of an enum.</li><li>Enum values are all instances of the same class and thus <strong>cannot hold distinct properties</strong> beyond simple values.</li></ul><h4>Enum Class with Properties and Methods</h4><p>You can also add properties or methods to an enum if you need more complexity, but this flexibility is limited.</p><pre>enum class TrafficLight(val duration: Int) {<br>    RED(30),<br>    YELLOW(5),<br>    GREEN(25);<br><br>    fun nextLight() = when (this) {<br>        RED -&gt; YELLOW<br>        YELLOW -&gt; GREEN<br>        GREEN -&gt; RED<br>    }<br>}</pre><h3>Sealed Classes</h3><p>A sealed class in Kotlin restricts the inheritance of subclasses, meaning only specific subclasses of a sealed class are allowed, and all of these subclasses must be defined in the same file. This feature makes sealed classes ideal for representing restricted hierarchies where each subclass represents a specific type or state.</p><p><strong>Example:</strong></p><pre>sealed class Operation {<br>    class Add(val value: Int) : Operation()<br>    class Subtract(val value: Int) : Operation()<br>    object Reset : Operation()<br>}</pre><h4>When to Use Sealed Classes</h4><p>Use a sealed class when:</p><ul><li>You need a restricted set of types that can hold varying properties or behavior.</li><li>The values are complex and might contain different types or properties.</li><li>You’re representing states, results, or actions that may carry data, like Success and Failure in a network response.</li></ul><p><strong>Example Scenario</strong>: Representing different states of a network response, such as Success and Error, where each state might carry additional data (e.g., a result or error message).</p><h4>Advantages of Sealed Classes</h4><ul><li>Sealed classes <strong>allow subclassing</strong>, enabling each subclass to hold different properties and behavior.</li><li>They provide a <strong>type-safe way to represent different states</strong> or types that are related but distinct.</li><li>Pattern matching with when statements is exhaustive, ensuring all cases are handled, enhancing code safety.</li></ul><h3>Choosing Between Enum and Sealed Classes</h3><ol><li><strong>For Simple, Fixed Sets</strong>: Choose an enum class when dealing with a small, fixed set of simple constants that don’t require distinct properties or behaviors (e.g., days of the week, predefined status codes).</li><li><strong>For Complex Hierarchies</strong>: Use a sealed class when your values represent states or entities with varying properties, particularly when these might evolve over time (e.g., network response states, commands in a state machine).</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93920d2e4e8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Kotlin Coroutines Cheat Sheet for Android Engineers]]></title>
            <link>https://medium.com/@cabanas.ignacio/advanced-kotlin-coroutines-cheat-sheet-for-android-engineers-1fc36b21bf9b?source=rss-667f6151b7d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fc36b21bf9b</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android-developers]]></category>
            <category><![CDATA[android-engineer]]></category>
            <dc:creator><![CDATA[Ignacio Cabanas]]></dc:creator>
            <pubDate>Fri, 11 Oct 2024 15:34:07 GMT</pubDate>
            <atom:updated>2024-10-11T15:34:07.741Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0Zj4_KNPXH_qygbp" /></figure><p>This cheat sheet serves as a quick reference to advanced coroutine concepts, designed to help you tackle complex scenarios in Android development.</p><h3>Coroutine Basics Refresher</h3><p>Before diving into advanced topics, let&#39;s briefly revisit some fundamental concepts:</p><ul><li><strong>Coroutine</strong>: A lightweight thread that can be suspended and resumed.</li><li><strong>Suspend Function</strong>: A function that can be paused and resumed later.</li><li><strong>CoroutineScope</strong>: Defines the lifecycle and context for coroutines.</li></ul><h3>Key Concepts</h3><h4>Coroutine Context</h4><p>A <strong>CoroutineContext</strong> is a set of elements that define the behavior of a coroutine, such as its <strong>Job</strong> and <strong>Dispatcher</strong>.</p><ul><li><strong>Job</strong>: Manages the lifecycle of the coroutine, including cancellation.</li><li><strong>Dispatcher</strong>: Determines the thread or threads the coroutine uses.</li></ul><h4>Job</h4><ul><li>Represents a cancellable task.</li><li>Every coroutine has its own Job.</li><li>Parent coroutines wait for their children coroutines to complete.</li></ul><h4>Dispatchers</h4><ul><li><strong>Dispatchers.Main</strong>: Runs coroutines on the main Android thread.</li><li><strong>Dispatchers.IO</strong>: Optimized for offloading blocking I/O tasks.</li><li><strong>Dispatchers.Default</strong>: Optimized for CPU-intensive work.</li><li><strong>Dispatchers.Unconfined</strong>: Starts the coroutine in the caller thread but only until the first suspension point.</li></ul><h4>Coroutine Scope</h4><p>Defines the lifecycle of coroutines and ties them to a component like ViewModel or Activity.</p><ul><li>Use predefined scopes like viewModelScope or lifecycleScope in Android.</li><li>Avoid using GlobalScope as it can lead to memory leaks.</li></ul><h3>Main Rules of Coroutines</h3><ol><li><strong>Always start coroutines within a CoroutineScope.</strong></li><li><strong>Child coroutines inherit context from their parent, except for the Job.</strong></li><li><strong>Parent coroutines wait for their children to complete.</strong></li><li><strong>Cancelling a parent coroutine cancels all its children.</strong></li><li><strong>Exceptions in child coroutines cancel the parent, unless using a SupervisorJob.</strong></li><li><strong>Do not pass CoroutineScopes around; instead, create scopes as needed using scope functions.</strong></li></ol><h3>Coroutine Scope Functions</h3><h4>coroutineScope</h4><ul><li>Suspends the current coroutine and creates a new scope.</li><li>Returns the result of the block.</li></ul><pre>suspend fun fetchData() = coroutineScope {<br>    val data = async { fetchFromNetwork() }<br>    data.await()<br>}</pre><h4>supervisorScope</h4><ul><li>Similar to coroutineScope, but child coroutines can fail independently without cancelling the parent.</li></ul><pre>suspend fun fetchAllData() = supervisorScope {<br>    val data1 = async { fetchFromNetwork1() }<br>    val data2 = async { fetchFromNetwork2() }<br>    // Even if one fails, the other continues<br>    data1.await() + data2.await()<br>}</pre><h4>withContext</h4><ul><li>Changes the coroutine context for the block.</li><li>Commonly used to switch dispatchers.</li></ul><pre>suspend fun readFile() = withContext(Dispatchers.IO) {<br>    // Read file from disk<br>}</pre><h4>withTimeout and withTimeoutOrNull</h4><ul><li>Limits the execution time of a coroutine.</li><li>Throws TimeoutCancellationException or returns null on timeout.</li></ul><pre>val result = withTimeoutOrNull(1000) {<br>    longRunningTask()<br>}</pre><h3>Dispatchers Deep Dive</h3><h4>Dispatchers.Main</h4><ul><li>Runs on the Android main thread.</li><li>Use for UI updates.</li><li>Be cautious not to perform heavy computations here.</li></ul><h4>Dispatchers.IO</h4><ul><li>Optimized for I/O operations.</li><li>Has a shared pool of threads.</li><li>Suitable for file I/O, network requests, database operations.</li></ul><h4>Dispatchers.Default</h4><ul><li>Optimized for CPU-intensive tasks.</li><li>Uses a pool of threads equal to the number of CPU cores.</li></ul><h4>Dispatchers.Unconfined</h4><ul><li>Starts in the caller thread.</li><li>Not confined to any specific thread after suspension.</li><li>Generally not recommended for production code.</li></ul><h3>Running Tasks in Parallel</h3><h4>Using async and await</h4><p>When you have access to a CoroutineScope (e.g., in a ViewModel):</p><pre>fun fetchUserData() {<br>    viewModelScope.launch {<br>        val userDeferred = async { getUserInfo() }<br>        val postsDeferred = async { getUserPosts() }<br>        val userInfo = userDeferred.await()<br>        val userPosts = postsDeferred.await()<br>        // Use userInfo and userPosts<br>    }<br>}</pre><h4>Without Access to a Scope</h4><p>When in a repository or use case:</p><pre>suspend fun fetchUserData(): Pair&lt;UserInfo, List&lt;Post&gt;&gt; = coroutineScope {<br>    val userDeferred = async { getUserInfo() }<br>    val postsDeferred = async { getUserPosts() }<br>    Pair(userDeferred.await(), postsDeferred.await())<br>}</pre><h3>Downloading Multiple Pages in Parallel</h3><pre>suspend fun fetchAllPages(totalPages: Int): List&lt;PageData&gt; = coroutineScope {<br>    (1..totalPages).map { page -&gt;<br>        async { fetchPageData(page) }<br>    }.awaitAll()<br>}</pre><h3>Handling Cancellation and Exceptions</h3><h4>Clean-Up on Cancellation</h4><p>Use try...finally to perform clean-up actions.</p><pre>viewModelScope.launch {<br>    try {<br>        performTask()<br>    } finally {<br>        // This block executes on cancellation<br>        withContext(NonCancellable) {<br>            cleanUpResources()<br>        }<br>    }<br>}</pre><h4>Cancellation Exception Propagation</h4><ul><li>By default, a CancellationException does not cancel the parent coroutine.</li><li>You can create custom exceptions by extending CancellationException.</li></ul><h4>Defining Default Exception Handling</h4><p>Use CoroutineExceptionHandler to handle uncaught exceptions.</p><pre>val handler = CoroutineExceptionHandler { _, exception -&gt;<br>    // Handle exception, e.g., log out user on 401 error<br>}<br>val scope = CoroutineScope(SupervisorJob() + handler)<br>scope.launch {<br>    // Coroutine code<br>}</pre><h3>SupervisorJob and SupervisorScope</h3><h4>Using SupervisorJob</h4><p>Allows child coroutines to fail independently.</p><pre>val supervisor = SupervisorJob()<br>val scope = CoroutineScope(supervisor + Dispatchers.Main)<br>scope.launch {<br>    // Child coroutines here<br>}</pre><h4>Using supervisorScope</h4><p>Within a suspending function:</p><pre>suspend fun performTasks() = supervisorScope {<br>    val task1 = launch { taskOne() }<br>    val task2 = launch { taskTwo() }<br>    // If taskOne fails, taskTwo continues<br>}</pre><h3>Best Practices</h3><h4>Avoid GlobalScope</h4><ul><li>Using GlobalScope can lead to memory leaks.</li><li>Always tie your coroutines to a lifecycle-aware scope.</li></ul><h4>Do Not Pass CoroutineScopes</h4><ul><li>Instead of passing scopes, use scope functions like coroutineScope or supervisorScope.</li></ul><h4>Limit Thread Switching</h4><ul><li>Avoid unnecessary dispatcher switches to improve performance.</li><li>Use Dispatchers.Main.immediate to check if you&#39;re already on the main thread.</li></ul><pre>suspend fun updateUI() = withContext(Dispatchers.Main.immediate) {<br>    // UI update code<br>}</pre><h4>Handling Shared Mutable State</h4><p>Use thread-safe constructs to manage shared data.</p><ul><li><strong>Atomic Variables</strong></li></ul><pre>val atomicCounter = AtomicInteger(0)<br><br>suspend fun incrementCounter() {<br>    atomicCounter.incrementAndGet()<br>}</pre><ul><li><strong>Mutex</strong></li></ul><pre>val mutex = Mutex()<br>var counter = 0<br><br>suspend fun incrementCounter() {<br>    mutex.withLock {<br>        counter++<br>    }<br>}</pre><p>By understanding and applying these advanced coroutine concepts, you’ll be better equipped to handle complex concurrency scenarios in your Android applications.</p><p><strong><em>Note: </em></strong><em>Always keep your Kotlin and coroutine libraries up to date to leverage the latest features and improvements.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fc36b21bf9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVVM and MVI Explained: Key Differences for Android Developers]]></title>
            <link>https://medium.com/@cabanas.ignacio/mvvm-and-mvi-explained-key-differences-for-android-developers-6ca09df77b21?source=rss-667f6151b7d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ca09df77b21</guid>
            <category><![CDATA[mvi]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Ignacio Cabanas]]></dc:creator>
            <pubDate>Mon, 17 Jun 2024 14:42:37 GMT</pubDate>
            <atom:updated>2024-06-17T14:42:37.150Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iBRdJiqW0P7vTK3K088fBg.png" /></figure><h3>Introduction</h3><p>Model-View-ViewModel (MVVM) and Model-View-Intent (MVI) are two popular architectural patterns used in Android development. Both aim to separate concerns and make code more maintainable, but they have different approaches and use cases. This article explores the key differences, with detailed explanations, code examples, pros and cons, and a conclusion to help you choose the right pattern for your project.</p><h3>Pattern Overview</h3><h4>MVVM (Model-View-ViewModel)</h4><p>MVVM separates the application logic into three main components: Model, View, and ViewModel. The Model represents the data and business logic. The View is the UI layer that observes the ViewModel. The ViewModel acts as a bridge between the Model and the View, managing the UI-related data and handling the logic to update the View.</p><ul><li><strong>Model:</strong> The Model encapsulates the data and business logic of the application. It can include data sources such as databases or network APIs.</li><li><strong>ViewModel:</strong> The ViewModel holds the data required for the View and handles the logic to update the View. It uses LiveData to observe data changes and update the UI accordingly.</li><li><strong>View:</strong> The View is the UI component that observes the ViewModel. It updates the UI based on the changes in the data provided by the ViewModel.</li></ul><p><strong>Code Example:</strong></p><pre>// Model<br>data class Book(val title: String, val author: String)<br><br>class BookRepository {<br>    fun getBooks(): List&lt;Book&gt; {<br>        // Simulate fetching data from a data source<br>        return listOf(Book(&quot;Title 1&quot;, &quot;Author 1&quot;), Book(&quot;Title 2&quot;, &quot;Author 2&quot;))<br>    }<br>}<br><br>// ViewModel<br>class BookViewModel(private val bookRepository: BookRepository) : ViewModel() {<br>    private val _books = MutableLiveData&lt;List&lt;Book&gt;&gt;()<br>    val books: LiveData&lt;List&lt;Book&gt;&gt; get() = _books<br><br>    fun loadBooks() {<br>        // Load books from the repository<br>        _books.value = bookRepository.getBooks()<br>    }<br>}<br><br>// View (Activity or Fragment)<br>class BookFragment : Fragment() {<br>    private lateinit var viewModel: BookViewModel<br><br>    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {<br>        super.onViewCreated(view, savedInstanceState)<br>        viewModel = ViewModelProvider(this, ViewModelFactory(BookRepository())).get(BookViewModel::class.java)<br>        <br>        // Observe books LiveData<br>        viewModel.books.observe(viewLifecycleOwner, Observer { books -&gt;<br>            // Update UI with the list of books<br>        })<br>        <br>        // Load books<br>        viewModel.loadBooks()<br>    }<br>}</pre><p><strong>Pros:</strong></p><ul><li><strong>Separation of Concerns:</strong> Clear separation between UI and business logic.</li><li><strong>Two-Way Data Binding:</strong> Simplifies UI updates and reduces boilerplate code.</li><li><strong>Testable:</strong> ViewModel is easy to unit test since it is decoupled from the Android framework.</li></ul><p><strong>Cons:</strong></p><ul><li><strong>Complex Data Binding:</strong> Can become complex in large applications.</li><li><strong>Lifecycle Awareness:</strong> Needs to handle lifecycle events properly to avoid memory leaks and crashes.</li></ul><h4>MVI (Model-View-Intent)</h4><p>MVI is based on the concept of unidirectional data flow. It separates the application logic into three main components: Model, View, and Intent. The Model represents the state of the application. The View emits intents (user actions) and observes states. The Intent represents user actions or events.</p><ul><li><strong>Model:</strong> The Model holds the state of the application. It is immutable and updated through a reducer function.</li><li><strong>Intent:</strong> The Intent represents user actions or events. These intents are processed to produce new states.</li><li><strong>View:</strong> The View emits intents based on user actions and observes the state to render the UI.</li></ul><p><strong>Code Example:</strong></p><pre>// Model<br>data class Book(val title: String, val author: String)<br>data class BookState(val books: List&lt;Book&gt;, val isLoading: Boolean, val error: String?)<br><br>// View (Activity or Fragment)<br>class BookFragment : Fragment() {<br>    private lateinit var viewModel: BookViewModel<br><br>    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {<br>        super.onViewCreated(view, savedInstanceState)<br>        viewModel = ViewModelProvider(this).get(BookViewModel::class.java)<br><br>        // Observe state<br>        lifecycleScope.launchWhenStarted {<br>            viewModel.state.collect { state -&gt;<br>                render(state)<br>            }<br>        }<br><br>        // Emit intent<br>        view.findViewById&lt;Button&gt;(R.id.loadBooksButton).setOnClickListener {<br>            lifecycleScope.launch {<br>                viewModel.processIntent(BookIntent.LoadBooks)<br>            }<br>        }<br>    }<br><br>    private fun render(state: BookState) {<br>        // Render state to UI<br>        // Example: update a RecyclerView with the list of books<br>    }<br>}<br><br>// ViewModel<br>sealed class BookIntent {<br>    object LoadBooks : BookIntent()<br>}<br><br>class BookViewModel : ViewModel() {<br>    private val _state = MutableStateFlow(BookState(emptyList(), isLoading = false, error = null))<br>    val state: StateFlow&lt;BookState&gt; get() = _state<br><br>    fun processIntent(intent: BookIntent) {<br>        when (intent) {<br>            is BookIntent.LoadBooks -&gt; loadBooks()<br>        }<br>    }<br><br>    private fun loadBooks() {<br>        viewModelScope.launch {<br>            _state.value = BookState(emptyList(), isLoading = true, error = null)<br>            // Simulate data loading<br>            delay(1000)<br>            _state.value = BookState(listOf(Book(&quot;Title 1&quot;, &quot;Author 1&quot;), Book(&quot;Title 2&quot;, &quot;Author 2&quot;)), isLoading = false, error = null)<br>        }<br>    }<br>}</pre><h3>Key Differences</h3><h4><strong>State Management</strong></h4><ul><li><strong>MVVM:</strong> Uses two-way data binding with LiveData. The ViewModel exposes LiveData objects that the View observes.</li><li><strong>MVI:</strong> Uses unidirectional data flow. The View emits intents that trigger state changes, and the View observes the immutable state.</li></ul><h4><strong>UI Framework Compatibility</strong></h4><ul><li><strong>MVVM:</strong> Works well with both traditional XML layouts and Jetpack Compose.</li><li><strong>MVI:</strong> Particularly well-suited for Jetpack Compose due to its unidirectional data flow and immutable state management, which align with the declarative nature of Compose.</li></ul><h4><strong>Complexity</strong></h4><ul><li><strong>MVVM:</strong> Simpler and easier to implement, especially for straightforward UI updates.</li><li><strong>MVI:</strong> More complex, with a steeper learning curve, but provides better state management for complex applications.</li></ul><h4><strong>Testability</strong></h4><ul><li><strong>MVVM:</strong> ViewModel is easily testable due to the separation of concerns.</li><li><strong>MVI:</strong> Also testable, but requires testing both state management and intent processing.</li></ul><h4><strong>Scalability</strong></h4><ul><li><strong>MVVM:</strong> Scales well for medium-sized applications but can become cumbersome with very complex UIs.</li><li><strong>MVI:</strong> Scales better for large and complex applications with numerous user interactions and state changes.</li></ul><h3>Conclusion</h3><p>Choosing between MVVM and MVI depends on the specific needs of your project and the UI framework you are using. MVVM is well-suited for simpler applications with straightforward UI updates and works well with both XML layouts and Jetpack Compose. MVI, on the other hand, offers a more robust and scalable solution for complex applications with numerous user interactions and state changes, and it aligns more naturally with Jetpack Compose’s declarative UI approach.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ca09df77b21" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>