{"id":166,"date":"2026-10-18T13:59:00","date_gmt":"2026-10-18T13:59:00","guid":{"rendered":"https:\/\/moiks.com\/blog\/?p=166"},"modified":"2026-11-06T08:48:30","modified_gmt":"2026-11-06T08:48:30","slug":"kotlin-flow-exception-handling-retry-in-android-complete-guide","status":"publish","type":"post","link":"https:\/\/moiks.com\/blog\/kotlin-flow-exception-handling-retry-in-android-complete-guide\/","title":{"rendered":"Kotlin Flow Exception Handling &#038; Retry in Android: Complete Guide"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Handling errors is an essential part of building reliable Android applications.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In real-world applications, asynchronous operations can fail for many reasons:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Internet connection problems<\/li>\n\n\n\n<li>API server errors<\/li>\n\n\n\n<li>Request timeouts<\/li>\n\n\n\n<li>Database failures<\/li>\n\n\n\n<li>Invalid responses<\/li>\n\n\n\n<li>Authentication errors<\/li>\n\n\n\n<li>Temporary service interruptions<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">If these errors are not handled correctly, users may experience unexpected application behavior or crashes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Kotlin Flow provides powerful operators for handling exceptions and retrying failed operations.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The most important operators include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>catch()<\/code><\/li>\n\n\n\n<li><code>retry()<\/code><\/li>\n\n\n\n<li><code>retryWhen()<\/code><\/li>\n\n\n\n<li><code>onCompletion()<\/code><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">In this tutorial, we&#8217;ll learn how these operators work and how to use them with <strong>Kotlin Coroutines, ViewModel, StateFlow, and Jetpack Compose<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We&#8217;ll also build a practical Android mini-project that demonstrates error handling and retry functionality.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What You&#8217;ll Learn<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">By the end of this tutorial, you&#8217;ll understand:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Why exception handling matters in Kotlin Flow<\/li>\n\n\n\n<li>How Flow exceptions propagate<\/li>\n\n\n\n<li>How catch() works<\/li>\n\n\n\n<li>Upstream vs downstream exceptions<\/li>\n\n\n\n<li>How retry() works<\/li>\n\n\n\n<li>How retryWhen() works<\/li>\n\n\n\n<li>Retry with exponential backoff<\/li>\n\n\n\n<li>Handling CancellationException<\/li>\n\n\n\n<li>Handling network failures<\/li>\n\n\n\n<li>Using onCompletion()<\/li>\n\n\n\n<li>Representing loading, success, and error states<\/li>\n\n\n\n<li>Flow exception handling with ViewModel<\/li>\n\n\n\n<li>Jetpack Compose error and retry UI<\/li>\n\n\n\n<li>Common mistakes<\/li>\n\n\n\n<li>Production best practices<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s begin!<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">1. Why Exception Handling Matters in Kotlin Flow<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Consider an Android application that fetches products from a REST API.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The application requests product information.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, the request may fail because the device loses internet connectivity.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Without proper error handling, the application may fail to display meaningful feedback.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A better approach is to represent the operation&#8217;s status explicitly.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Typical Flow<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>User Opens Screen\n        |\n        v\nViewModel Requests Data\n        |\n        v\nRepository Calls API\n        |\n        +------ Success ------&gt; Display Data\n        |\n        +------ Failure ------&gt; Show Error\n                                  |\n                                  v\n                              Retry Action<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits of Proper Error Handling<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Prevents unhandled failures<\/li>\n\n\n\n<li>Provides meaningful feedback<\/li>\n\n\n\n<li>Supports retry functionality<\/li>\n\n\n\n<li>Improves user experience<\/li>\n\n\n\n<li>Makes asynchronous operations predictable<\/li>\n\n\n\n<li>Simplifies debugging and testing<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">2. Understanding Exceptions in Kotlin Flow<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A Flow can throw exceptions while producing or transforming values.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>fun numbersFlow(): Flow&lt;Int&gt; = flow {\n\n    emit(1)\n\n    emit(2)\n\n    throw IllegalStateException(\n        \"Something went wrong\"\n    )\n\n    emit(3)\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Collecting the Flow<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>fun main() = runBlocking {\n\n    try {\n\n        numbersFlow().collect { value -&gt;\n\n            println(value)\n        }\n\n    } catch (exception: Exception) {\n\n        println(\n            \"Error: ${exception.message}\"\n        )\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Output<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>1\n2\nError: Something went wrong<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The Flow emits values 1 and 2.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Then an exception occurs.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The Flow stops emitting values, and the exception propagates to the collector.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The value 3 is never emitted.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">3. Kotlin Flow catch() Operator<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>catch()<\/code> operator handles exceptions from upstream Flow operations.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>fun main() = runBlocking {\n\n    flow {\n\n        emit(10)\n\n        emit(20)\n\n        throw IllegalStateException(\n            \"Data loading failed\"\n        )\n\n    }.catch { exception -&gt;\n\n        println(\n            \"Caught: ${exception.message}\"\n        )\n\n    }.collect { value -&gt;\n\n        println(value)\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Output<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>10\n20\nCaught: Data loading failed<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The catch operator intercepts the upstream exception.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Instead of allowing it to propagate to the caller, we handle it inside catch.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Practical Uses<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Network error handling<\/li>\n\n\n\n<li>Database failures<\/li>\n\n\n\n<li>Data transformation errors<\/li>\n\n\n\n<li>Providing fallback values<\/li>\n\n\n\n<li>Converting exceptions into UI states<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">4. Emitting Fallback Values with catch()<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The catch operator can emit a fallback value after an upstream failure.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>fun main() = runBlocking {\n\n    flow {\n\n        emit(\"Android\")\n\n        throw IllegalStateException(\n            \"Server unavailable\"\n        )\n\n    }.catch {\n\n        emit(\"Offline Mode\")\n\n    }.collect {\n\n        println(it)\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Output<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Android\nOffline Mode<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The Flow initially emits Android.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When an exception occurs, catch emits Offline Mode.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Emitting a fallback value does not automatically restart the failed upstream Flow.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The stream normally completes after the fallback emission.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use retry operators when an upstream operation should be attempted again.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">5. Upstream vs Downstream Exceptions<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Understanding exception propagation is essential.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The catch operator handles exceptions from operators placed before it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It does not catch exceptions thrown by downstream collectors.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>fun main() = runBlocking {\n\n    flowOf(1, 2, 3)\n\n        .catch { exception -&gt;\n\n            println(\n                \"Caught: ${exception.message}\"\n            )\n        }\n\n        .collect { value -&gt;\n\n            if (value == 2) {\n\n                throw IllegalStateException(\n                    \"Collector failed\"\n                )\n            }\n\n            println(value)\n        }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The exception occurs inside collect.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Because collect is downstream from catch, the catch operator does not intercept it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The exception propagates to the caller.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Correct Approach<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">If the collector itself can fail, handle its exception at the collection boundary.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Alternatively, move the relevant processing into an upstream operator when that fits the application&#8217;s design.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>flowOf(1, 2, 3)\n\n    .map { value -&gt;\n\n        if (value == 2) {\n\n            throw IllegalStateException(\n                \"Processing failed\"\n            )\n        }\n\n        value\n    }\n\n    .catch { exception -&gt;\n\n        println(\n            \"Caught: ${exception.message}\"\n        )\n    }\n\n    .collect { value -&gt;\n\n        println(value)\n    }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Now catch can handle the exception thrown by map.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">6. Kotlin Flow retry() Operator<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>retry()<\/code> operator restarts upstream Flow collection when an exception occurs and the retry condition allows it.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>fun main() = runBlocking {\n\n    var attempts = 0\n\n    flow {\n\n        attempts++\n\n        println(\"Attempt: $attempts\")\n\n        if (attempts &lt; 3) {\n\n            throw IllegalStateException(\n                \"Temporary failure\"\n            )\n        }\n\n        emit(\"Success\")\n\n    }.retry(\n        retries = 2\n    ).collect {\n\n        println(it)\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Output<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Attempt: 1\nAttempt: 2\nAttempt: 3\nSuccess<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The first attempt fails.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The second attempt also fails.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The third attempt succeeds.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>retries = 2<\/code> means two additional attempts after the initial collection.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The maximum number of attempts in this example is three.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">7. Conditional Retry with retry()<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Not every exception should trigger a retry.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Temporary server failures may be retryable.<\/li>\n\n\n\n<li>Invalid user credentials generally require user action.<\/li>\n\n\n\n<li>Invalid request data should not be retried without correction.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>flow {\n\n    emit(fetchData())\n\n}.retry(\n    retries = 3\n) { exception -&gt;\n\n    exception is IOException\n\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This retries only when the exception is an IOException.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The Flow does not retry other exception types.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">IOException can represent different failure conditions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In production, classify failures carefully rather than treating every IOException as retryable.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">8. Kotlin Flow retryWhen() Operator<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>retryWhen()<\/code> operator provides more control over retry behavior.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It receives:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The exception<\/li>\n\n\n\n<li>The current retry attempt index<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>fun main() = runBlocking {\n\n    var requestCount = 0\n\n    flow {\n\n        requestCount++\n\n        if (requestCount &lt; 3) {\n\n            throw IOException(\n                \"Network unavailable\"\n            )\n        }\n\n        emit(\"Data loaded\")\n\n    }.retryWhen { cause, attempt -&gt;\n\n        println(\n            \"Retry attempt: ${attempt + 1}\"\n        )\n\n        cause is IOException &amp;&amp; attempt &lt; 2\n\n    }.collect {\n\n        println(it)\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Output<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Retry attempt: 1\nRetry attempt: 2\nData loaded<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The retryWhen operator receives the failure and the number of previous retries.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The first retry has attempt index 0.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The second retry has attempt index 1.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When the condition returns true, upstream collection starts again.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">9. Retry with Delay<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Immediate retries are not always appropriate.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If a server is temporarily unavailable, retrying continuously may increase unnecessary load.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A delay between attempts is often more appropriate.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>flow {\n\n    emit(fetchData())\n\n}.retryWhen { cause, attempt -&gt;\n\n    if (\n        cause is IOException &amp;&amp;\n        attempt &lt; 3\n    ) {\n\n        delay(1000)\n\n        true\n\n    } else {\n\n        false\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The Flow waits one second between retry attempts.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This provides a simple fixed-delay retry strategy.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">10. Exponential Backoff in Kotlin Flow<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Exponential backoff increases the waiting time between retries.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Retry<\/th><th>Delay<\/th><\/tr><tr><td>First<\/td><td>1 second<\/td><\/tr><tr><td>Second<\/td><td>2 seconds<\/td><\/tr><tr><td>Third<\/td><td>4 seconds<\/td><\/tr><tr><td>Fourth<\/td><td>8 seconds<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Why Use Exponential Backoff?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">It helps reduce repeated requests when a service is temporarily unavailable.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is commonly used for:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Network requests<\/li>\n\n\n\n<li>Remote API calls<\/li>\n\n\n\n<li>Temporary server failures<\/li>\n\n\n\n<li>Rate-limited operations<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>flow {\n\n    emit(fetchData())\n\n}.retryWhen { cause, attempt -&gt;\n\n    if (\n        cause is IOException &amp;&amp;\n        attempt &lt; 4\n    ) {\n\n        val delayMillis =\n            1000L * (1L shl attempt.toInt())\n\n        delay(delayMillis)\n\n        true\n\n    } else {\n\n        false\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The delay increases after each failed attempt.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Production Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For real network applications:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Limit the maximum retry count.<\/li>\n\n\n\n<li>Cap the maximum delay.<\/li>\n\n\n\n<li>Consider adding random jitter.<\/li>\n\n\n\n<li>Respect server Retry-After instructions.<\/li>\n\n\n\n<li>Retry only appropriate failures.<\/li>\n\n\n\n<li>Avoid retrying non-idempotent operations without safeguards.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">11. Handling CancellationException<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Coroutine cancellation is an important part of Kotlin Coroutines.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When a coroutine is cancelled, it commonly throws CancellationException.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Cancellation should normally propagate.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Incorrect Approach<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>try {\n\n    performOperation()\n\n} catch (exception: Exception) {\n\n    \/\/ Ignoring every exception\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This can accidentally swallow cancellation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Recommended Approach<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>try {\n\n    performOperation()\n\n} catch (exception: CancellationException) {\n\n    throw exception\n\n} catch (exception: Exception) {\n\n    println(\n        \"Operation failed: ${exception.message}\"\n    )\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">CancellationException is rethrown.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Other exceptions can be handled normally.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Kotlin Flow catch and retry operators are designed to respect coroutine cancellation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When writing your own try\/catch blocks, preserve cancellation explicitly.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">12. Kotlin Flow onCompletion()<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>onCompletion()<\/code> operator executes when a Flow collection completes, fails, or is cancelled.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>fun main() = runBlocking {\n\n    flowOf(1, 2, 3)\n\n        .onCompletion { cause -&gt;\n\n            if (cause == null) {\n\n                println(\"Completed successfully\")\n\n            } else {\n\n                println(\"Flow terminated: $cause\")\n            }\n        }\n\n        .collect {\n\n            println(it)\n        }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Output<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>1\n2\n3\nCompleted successfully<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The cause parameter is null when the Flow completes normally.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Otherwise, it contains the exception responsible for termination.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">onCompletion is not a replacement for catch.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is primarily used to observe completion and perform appropriate cleanup or finalization.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">13. Combining retryWhen() and catch()<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A common production pattern is to retry appropriate failures and then convert the final failure into an error state.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>flow {\n\n    emit(fetchData())\n\n}\n\n    .retryWhen { cause, attempt -&gt;\n\n        if (\n            cause is IOException &amp;&amp;\n            attempt &lt; 3\n        ) {\n\n            delay(1000)\n\n            true\n\n        } else {\n\n            false\n        }\n    }\n\n    .catch { exception -&gt;\n\n        println(\n            \"Final failure: ${exception.message}\"\n        )\n    }\n\n    .collect { result -&gt;\n\n        println(result)\n    }<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">First, the Flow attempts the operation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If a retryable failure occurs, retryWhen restarts upstream collection.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When retries are exhausted, the exception reaches catch.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The application can then display an error state.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For a typical retry pipeline, place retryWhen before catch.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">14. Handling Network Errors in Android<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Real Android applications frequently use Retrofit for API communication.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Different failures may require different handling strategies.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Common Network Errors<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Error<\/th><th>Typical Action<\/th><\/tr><tr><td>No internet connection<\/td><td>Show connectivity error<\/td><\/tr><tr><td>Connection timeout<\/td><td>Offer retry<\/td><\/tr><tr><td>HTTP 401<\/td><td>Handle authentication<\/td><\/tr><tr><td>HTTP 403<\/td><td>Show permission error<\/td><\/tr><tr><td>HTTP 404<\/td><td>Show not-found state<\/td><\/tr><tr><td>HTTP 429<\/td><td>Respect rate limits<\/td><\/tr><tr><td>HTTP 500<\/td><td>Consider retry<\/td><\/tr><tr><td>HTTP 503<\/td><td>Consider retry with backoff<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Example Error Classification<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>sealed interface NetworkError {\n\n    data object NoConnection : NetworkError\n\n    data object Unauthorized : NetworkError\n\n    data object ServerError : NetworkError\n\n    data object Unknown : NetworkError\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid displaying raw exception messages directly to users.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Convert technical failures into understandable UI messages.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">15. Loading, Success, and Error UI States<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A reliable Android screen should represent its state explicitly.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>sealed interface UiState&lt;out T&gt; {\n\n    data object Loading : UiState&lt;Nothing&gt;\n\n    data class Success&lt;T&gt;(\n        val data: T\n    ) : UiState&lt;T&gt;\n\n    data class Error(\n        val message: String\n    ) : UiState&lt;Nothing&gt;\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The screen can display one of three states:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Loading<\/li>\n\n\n\n<li>Success<\/li>\n\n\n\n<li>Error<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">This pattern works naturally with StateFlow and Jetpack Compose.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">Practical Android Mini-Project: Product Loading with Retry<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Now let&#8217;s build a simple Android application that demonstrates:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Loading products<\/li>\n\n\n\n<li>Simulating network failures<\/li>\n\n\n\n<li>Automatic retry<\/li>\n\n\n\n<li>Exponential backoff<\/li>\n\n\n\n<li>Manual retry<\/li>\n\n\n\n<li>ViewModel integration<\/li>\n\n\n\n<li>StateFlow UI state<\/li>\n\n\n\n<li>Jetpack Compose error handling<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Technology Stack<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Kotlin<\/li>\n\n\n\n<li>Kotlin Coroutines<\/li>\n\n\n\n<li>Kotlin Flow<\/li>\n\n\n\n<li>ViewModel<\/li>\n\n\n\n<li>StateFlow<\/li>\n\n\n\n<li>Jetpack Compose<\/li>\n\n\n\n<li>Material 3<\/li>\n\n\n\n<li>MVVM architecture<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">For simplicity, we&#8217;ll simulate a network repository.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">16. Create the Product Model<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>data class Product(\n    val id: Int,\n    val name: String,\n    val price: Double\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Each product contains:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>ID<\/li>\n\n\n\n<li>Name<\/li>\n\n\n\n<li>Price<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">17. Create the Product Repository<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">We&#8217;ll simulate a repository that fails twice before succeeding.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class ProductRepository {\n\n    private var requestCount = 0\n\n    fun getProducts(): Flow&lt;List&lt;Product&gt;&gt; = flow {\n\n        delay(500)\n\n        requestCount++\n\n        if (requestCount &lt;= 2) {\n\n            throw IOException(\n                \"Temporary network failure\"\n            )\n        }\n\n        emit(\n            listOf(\n                Product(1, \"Android Phone\", 19999.0),\n                Product(2, \"Bluetooth Speaker\", 2499.0),\n                Product(3, \"Smart Watch\", 4999.0),\n                Product(4, \"Wireless Headphones\", 2999.0)\n            )\n        )\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The first request fails.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The second request also fails.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The third request succeeds.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This helps demonstrate retry behavior.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This repository is a learning simulation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A real repository would call an API using Retrofit or another networking library.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">18. Create the Product UI State<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>sealed interface ProductUiState {\n\n    data object Loading : ProductUiState\n\n    data class Success(\n        val products: List&lt;Product&gt;\n    ) : ProductUiState\n\n    data class Error(\n        val message: String\n    ) : ProductUiState\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This sealed interface represents the complete screen state.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">19. Create the Product ViewModel<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>class ProductViewModel : ViewModel() {\n\n    private val repository = ProductRepository()\n\n    private val _uiState =\n        MutableStateFlow&lt;ProductUiState&gt;(\n            ProductUiState.Loading\n        )\n\n    val uiState: StateFlow&lt;ProductUiState&gt; =\n        _uiState.asStateFlow()\n\n    private var loadJob: Job? = null\n\n    init {\n        loadProducts()\n    }\n\n    fun loadProducts() {\n\n        loadJob?.cancel()\n\n        loadJob = viewModelScope.launch {\n\n            repository.getProducts()\n\n                .retryWhen { cause, attempt -&gt;\n\n                    if (\n                        cause is IOException &amp;&amp;\n                        attempt &lt; 3\n                    ) {\n\n                        val delayMillis =\n                            1000L * (1L shl attempt.toInt())\n\n                        delay(delayMillis)\n\n                        true\n\n                    } else {\n\n                        false\n                    }\n                }\n\n                .map&lt;List&lt;Product&gt;, ProductUiState&gt; { products -&gt;\n\n                    ProductUiState.Success(products)\n                }\n\n                .onStart {\n\n                    emit(ProductUiState.Loading)\n                }\n\n                .catch { exception -&gt;\n\n                    emit(\n                        ProductUiState.Error(\n                            message = \"Unable to load products. Please try again.\"\n                        )\n                    )\n                }\n\n                .collect { state -&gt;\n\n                    _uiState.value = state\n                }\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel starts loading products.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The repository initially fails.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">retryWhen automatically retries temporary failures.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When the operation succeeds, the ViewModel publishes a Success state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If all retries fail, catch converts the failure into an Error state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The UI observes the latest state through StateFlow.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why Track loadJob?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Cancelling the previous load operation prevents overlapping requests from updating the screen unexpectedly.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Production Note<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For production applications, inject the repository through the ViewModel constructor using Hilt.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Also, retry delays should be capped and network failures should be classified carefully.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">20. Create the Jetpack Compose Product Screen<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Now let&#8217;s create the UI.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@Composable\nfun ProductScreen(\n    viewModel: ProductViewModel = viewModel()\n) {\n\n    val uiState by viewModel.uiState\n        .collectAsStateWithLifecycle()\n\n    Column(\n        modifier = Modifier\n            .fillMaxSize()\n            .padding(20.dp)\n    ) {\n\n        Text(\n            text = \"Product Store\",\n            style = MaterialTheme.typography.headlineMedium\n        )\n\n        Spacer(\n            modifier = Modifier.height(24.dp)\n        )\n\n        when (val state = uiState) {\n\n            ProductUiState.Loading -&gt; {\n\n                Box(\n                    modifier = Modifier.fillMaxWidth(),\n                    contentAlignment = Alignment.Center\n                ) {\n\n                    CircularProgressIndicator()\n                }\n            }\n\n            is ProductUiState.Success -&gt; {\n\n                LazyColumn(\n                    verticalArrangement =\n                        Arrangement.spacedBy(12.dp)\n                ) {\n\n                    items(\n                        items = state.products,\n                        key = { product -&gt; product.id }\n                    ) { product -&gt;\n\n                        Card(\n                            modifier = Modifier.fillMaxWidth()\n                        ) {\n\n                            Column(\n                                modifier = Modifier.padding(16.dp)\n                            ) {\n\n                                Text(\n                                    text = product.name,\n                                    style = MaterialTheme.typography.titleMedium\n                                )\n\n                                Spacer(\n                                    modifier = Modifier.height(6.dp)\n                                )\n\n                                Text(\n                                    text = \"\u20b9${product.price}\",\n                                    style = MaterialTheme.typography.bodyLarge\n                                )\n                            }\n                        }\n                    }\n                }\n            }\n\n            is ProductUiState.Error -&gt; {\n\n                Text(\n                    text = state.message,\n                    color = MaterialTheme.colorScheme.error\n                )\n\n                Spacer(\n                    modifier = Modifier.height(16.dp)\n                )\n\n                Button(\n                    onClick = {\n                        viewModel.loadProducts()\n                    }\n                ) {\n\n                    Text(\"Retry\")\n                }\n            }\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The Compose screen observes the ViewModel&#8217;s StateFlow.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When the state is Loading, it displays a progress indicator.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When the state is Success, it displays a product list.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When the state is Error, it displays an error message and Retry button.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This provides a simple and predictable user experience.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">21. Required Imports<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Kotlin Coroutines and Flow<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import kotlinx.coroutines.Job\nimport kotlinx.coroutines.delay\nimport kotlinx.coroutines.launch\nimport kotlinx.coroutines.flow.Flow\nimport kotlinx.coroutines.flow.MutableStateFlow\nimport kotlinx.coroutines.flow.StateFlow\nimport kotlinx.coroutines.flow.asStateFlow\nimport kotlinx.coroutines.flow.catch\nimport kotlinx.coroutines.flow.collect\nimport kotlinx.coroutines.flow.flow\nimport kotlinx.coroutines.flow.map\nimport kotlinx.coroutines.flow.onStart\nimport kotlinx.coroutines.flow.retryWhen<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">ViewModel and Lifecycle<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import androidx.lifecycle.ViewModel\nimport androidx.lifecycle.viewModelScope\nimport androidx.lifecycle.viewmodel.compose.viewModel\nimport androidx.lifecycle.compose.collectAsStateWithLifecycle<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Jetpack Compose<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import androidx.compose.foundation.layout.Arrangement\nimport androidx.compose.foundation.layout.Box\nimport androidx.compose.foundation.layout.Column\nimport androidx.compose.foundation.layout.Spacer\nimport androidx.compose.foundation.layout.fillMaxSize\nimport androidx.compose.foundation.layout.fillMaxWidth\nimport androidx.compose.foundation.layout.height\nimport androidx.compose.foundation.layout.padding\nimport androidx.compose.foundation.lazy.LazyColumn\nimport androidx.compose.foundation.lazy.items\nimport androidx.compose.material3.Button\nimport androidx.compose.material3.Card\nimport androidx.compose.material3.CircularProgressIndicator\nimport androidx.compose.material3.MaterialTheme\nimport androidx.compose.material3.Text\nimport androidx.compose.runtime.Composable\nimport androidx.compose.runtime.getValue\nimport androidx.compose.ui.Alignment\nimport androidx.compose.ui.Modifier\nimport androidx.compose.ui.unit.dp<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Java IOException<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.io.IOException<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">22. Expected UI \u2014 Loading<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>+--------------------------------+\n|                                |\n|         Product Store          |\n|                                |\n|              \u25cb                 |\n|                                |\n|        Loading products...     |\n|                                |\n+--------------------------------+<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">23. Expected UI \u2014 Success<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>+--------------------------------+\n|                                |\n|         Product Store          |\n|                                |\n| +----------------------------+ |\n| | Android Phone              | |\n| | \u20b919999.0                   | |\n| +----------------------------+ |\n|                                |\n| +----------------------------+ |\n| | Bluetooth Speaker          | |\n| | \u20b92499.0                    | |\n| +----------------------------+ |\n|                                |\n| +----------------------------+ |\n| | Smart Watch                | |\n| | \u20b94999.0                    | |\n| +----------------------------+ |\n|                                |\n| +----------------------------+ |\n| | Wireless Headphones        | |\n| | \u20b92999.0                    | |\n| +----------------------------+ |\n|                                |\n+--------------------------------+<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">24. Expected UI \u2014 Error<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>+--------------------------------+\n|                                |\n|         Product Store          |\n|                                |\n|   Unable to load products.     |\n|        Please try again.       |\n|                                |\n|            &#91; Retry ]           |\n|                                |\n+--------------------------------+<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">25. How the Complete Application Works<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Step 1: Screen Opens<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Jetpack Compose requests the ViewModel.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 2: ViewModel Starts Loading<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel begins collecting the repository Flow.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 3: Repository Simulates Failure<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The first request throws IOException.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 4: retryWhen Handles Failure<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The retryWhen operator checks the exception and retry count.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 5: Exponential Backoff<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The Flow waits before retrying.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 6: Repository Retries<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The second request also fails.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 7: Final Attempt Succeeds<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The repository returns the product list.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 8: ViewModel Updates StateFlow<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel publishes ProductUiState.Success.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 9: Compose Displays Products<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The product list appears automatically.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If retries are exhausted, the screen displays an error state instead.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">26. Common Kotlin Flow Exception Handling Mistakes<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 1: Using catch() After collect()<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">catch must be part of the Flow pipeline.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It cannot intercept exceptions thrown by a downstream collect block.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 2: Retrying Every Exception<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Not every failure is temporary.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid retrying authentication failures, invalid requests, and other non-retryable conditions.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 3: Unlimited Retries<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Unlimited retries can waste resources and create a poor user experience.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Always consider retry limits.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 4: Ignoring CancellationException<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Cancellation must normally propagate.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid swallowing cancellation inside broad try\/catch blocks.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 5: Using Immediate Retries for Network Failures<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Repeated immediate retries can increase server load.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Consider delay or exponential backoff.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 6: Displaying Raw Exception Messages<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Technical exception messages may confuse users or expose internal details.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Display user-friendly messages.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 7: Ignoring Flow Operator Order<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The position of catch and retryWhen affects behavior.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Understand upstream and downstream exception handling.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 8: Performing Network Requests Directly in Composables<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use ViewModel and repository layers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 9: Forgetting Lifecycle-Aware Collection<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use collectAsStateWithLifecycle() when observing StateFlow in Android Compose.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 10: Treating retry() as a Universal Recovery Mechanism<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Retry is appropriate only when repeating an operation is safe and likely to succeed.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">27. Kotlin Flow Exception Handling Best Practices<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Follow these recommendations:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Handle failures at meaningful boundaries.<\/li>\n\n\n\n<li>Use catch() for upstream Flow exceptions.<\/li>\n\n\n\n<li>Use retry() for simple retry policies.<\/li>\n\n\n\n<li>Use retryWhen() for advanced retry logic.<\/li>\n\n\n\n<li>Preserve coroutine cancellation.<\/li>\n\n\n\n<li>Retry only appropriate exceptions.<\/li>\n\n\n\n<li>Limit retry attempts.<\/li>\n\n\n\n<li>Use capped exponential backoff for temporary failures.<\/li>\n\n\n\n<li>Respect server rate limits.<\/li>\n\n\n\n<li>Consider adding jitter to retry delays.<\/li>\n\n\n\n<li>Avoid exposing raw exception messages.<\/li>\n\n\n\n<li>Represent loading, success, and error states explicitly.<\/li>\n\n\n\n<li>Keep business logic inside ViewModels and repositories.<\/li>\n\n\n\n<li>Use lifecycle-aware StateFlow collection.<\/li>\n\n\n\n<li>Test success and failure scenarios.<\/li>\n\n\n\n<li>Avoid unnecessary repeated network requests.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">28. Kotlin Flow Exception Handling Quick Reference<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>API<\/th><th>Purpose<\/th><\/tr><tr><td>catch()<\/td><td>Handle upstream exceptions<\/td><\/tr><tr><td>retry()<\/td><td>Retry upstream collection<\/td><\/tr><tr><td>retryWhen()<\/td><td>Conditional retry with attempt count<\/td><\/tr><tr><td>onCompletion()<\/td><td>Observe Flow termination<\/td><\/tr><tr><td>CancellationException<\/td><td>Represents coroutine cancellation<\/td><\/tr><tr><td>IOException<\/td><td>Common network-related failure type<\/td><\/tr><tr><td>delay()<\/td><td>Suspend before retrying<\/td><\/tr><tr><td>StateFlow<\/td><td>Expose current UI state<\/td><\/tr><tr><td>viewModelScope<\/td><td>Manage ViewModel coroutines<\/td><\/tr><tr><td>collectAsStateWithLifecycle()<\/td><td>Lifecycle-aware Compose collection<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">29. Practical Exercises<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Try these exercises to strengthen your understanding.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 1: Basic catch()<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Create a Flow that throws an exception and handle it with catch().<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 2: Fallback Value<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Emit a fallback value when a Flow fails.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 3: retry()<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Create a Flow that fails twice and succeeds on the third attempt.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 4: Conditional Retry<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Retry only IOException failures.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 5: retryWhen()<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Log retry attempt numbers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 6: Fixed Delay<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Add a one-second delay between retries.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 7: Exponential Backoff<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Implement retry delays of one, two, and four seconds.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 8: Cancellation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Verify that coroutine cancellation is preserved.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 9: ViewModel<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Expose loading, success, and error states using StateFlow.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 10: Jetpack Compose<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Build the complete product loading mini-project with automatic and manual retry.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">30. Frequently Asked Questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">What is exception handling in Kotlin Flow?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Exception handling in Kotlin Flow involves managing failures that occur during Flow production, transformation, or collection.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What does catch() do in Kotlin Flow?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">catch() handles exceptions from upstream Flow operations.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does catch() handle exceptions inside collect()?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No. Exceptions thrown by downstream collect operations are not intercepted by an upstream catch operator.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What does retry() do?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">retry() restarts upstream Flow collection when an exception occurs and the retry condition allows it.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is retryWhen()?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">retryWhen() provides access to the exception and retry attempt count, allowing custom retry behavior.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is exponential backoff?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Exponential backoff increases the delay between retry attempts.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Should every network failure be retried?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No. Retry only when the operation is safe to repeat and the failure is likely temporary.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is CancellationException?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">CancellationException is commonly used to signal coroutine cancellation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is onCompletion()?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">onCompletion() observes whether Flow collection completed normally or terminated because of an exception or cancellation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can Flow exception handling be used with Jetpack Compose?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. ViewModels can convert Flow results and errors into StateFlow UI state, which Jetpack Compose observes.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What We&#8217;ve Learned<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In this tutorial, we learned:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Kotlin Flow exception propagation<\/li>\n\n\n\n<li>catch operator<\/li>\n\n\n\n<li>Upstream vs downstream exceptions<\/li>\n\n\n\n<li>Fallback values<\/li>\n\n\n\n<li>retry operator<\/li>\n\n\n\n<li>retryWhen operator<\/li>\n\n\n\n<li>Conditional retries<\/li>\n\n\n\n<li>Fixed-delay retries<\/li>\n\n\n\n<li>Exponential backoff<\/li>\n\n\n\n<li>CancellationException<\/li>\n\n\n\n<li>onCompletion<\/li>\n\n\n\n<li>Network error classification<\/li>\n\n\n\n<li>Loading, success, and error UI states<\/li>\n\n\n\n<li>ViewModel integration<\/li>\n\n\n\n<li>Jetpack Compose integration<\/li>\n\n\n\n<li>Product loading mini-project<\/li>\n\n\n\n<li>Common mistakes and best practices<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Proper error handling is essential for building reliable Android applications.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By combining Kotlin Flow exception operators with ViewModel, StateFlow, and Jetpack Compose, developers can create responsive applications that recover gracefully from temporary failures.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Understanding these concepts prepares you for production-ready networking, repository architecture, Retrofit integration, and advanced Android application development.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What&#8217;s Next?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In our next tutorial, we&#8217;ll explore:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Kotlin Flow Testing in Android: Turbine, runTest &amp; TestDispatchers<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You&#8217;ll learn:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Why Flow testing matters<\/li>\n\n\n\n<li>Testing cold Flows<\/li>\n\n\n\n<li>Testing StateFlow<\/li>\n\n\n\n<li>Testing SharedFlow<\/li>\n\n\n\n<li>kotlinx-coroutines-test<\/li>\n\n\n\n<li>runTest()<\/li>\n\n\n\n<li>StandardTestDispatcher<\/li>\n\n\n\n<li>UnconfinedTestDispatcher<\/li>\n\n\n\n<li>Testing Flow operators<\/li>\n\n\n\n<li>Testing debounce<\/li>\n\n\n\n<li>Testing retryWhen<\/li>\n\n\n\n<li>Turbine library<\/li>\n\n\n\n<li>ViewModel testing<\/li>\n\n\n\n<li>Practical Android unit tests<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Happy Coding!<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Continue learning modern Android development with <strong>Moiks Developer Blog<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Master Kotlin Flow error handling and retry strategies in Android. Learn catch, retry, retryWhen, CancellationException, exponential backoff, and production-ready error UI with ViewModel and Jetpack Compose.<\/p>\n","protected":false},"author":1,"featured_media":167,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":0,"footnotes":""},"categories":[3,333,7],"tags":[],"class_list":["post-166","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-android-development","category-android-tutorials","category-coroutines-flow"],"_links":{"self":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/166","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/comments?post=166"}],"version-history":[{"count":1,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/166\/revisions"}],"predecessor-version":[{"id":168,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/166\/revisions\/168"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/media\/167"}],"wp:attachment":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/media?parent=166"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/categories?post=166"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/tags?post=166"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}