{"id":172,"date":"2026-10-19T06:26:00","date_gmt":"2026-10-19T06:26:00","guid":{"rendered":"https:\/\/moiks.com\/blog\/?p=172"},"modified":"2026-11-06T08:48:29","modified_gmt":"2026-11-06T08:48:29","slug":"kotlin-coroutines-flow-best-practices-in-android-structured-concurrency-cancellation-performance","status":"publish","type":"post","link":"https:\/\/moiks.com\/blog\/kotlin-coroutines-flow-best-practices-in-android-structured-concurrency-cancellation-performance\/","title":{"rendered":"Kotlin Coroutines &#038; Flow Best Practices in Android: Structured Concurrency, Cancellation &#038; Performance"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Kotlin Coroutines and Flow are essential technologies for building modern Android applications.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">They simplify asynchronous programming and help developers manage background operations, API requests, database access, and reactive UI updates.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, simply using coroutines does not automatically make an application efficient or reliable.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Poor coroutine management can lead to:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Memory leaks<\/li>\n\n\n\n<li>Unnecessary background operations<\/li>\n\n\n\n<li>Unexpected application crashes<\/li>\n\n\n\n<li>Wasted CPU resources<\/li>\n\n\n\n<li>UI performance issues<\/li>\n\n\n\n<li>Incorrect cancellation behavior<\/li>\n\n\n\n<li>Duplicate network requests<\/li>\n\n\n\n<li>Difficult-to-debug concurrency problems<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">To build production-quality Android applications, developers must understand how to manage coroutine lifecycles, dispatchers, cancellation, exceptions, and Flow collection correctly.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this tutorial, we&#8217;ll explore the most important Kotlin Coroutines and Flow best practices using practical Android examples.<\/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>Structured concurrency<\/li>\n\n\n\n<li>CoroutineScope ownership<\/li>\n\n\n\n<li>viewModelScope<\/li>\n\n\n\n<li>lifecycleScope<\/li>\n\n\n\n<li>repeatOnLifecycle()<\/li>\n\n\n\n<li>Coroutine cancellation<\/li>\n\n\n\n<li>Cooperative cancellation<\/li>\n\n\n\n<li>SupervisorJob<\/li>\n\n\n\n<li>Exception handling<\/li>\n\n\n\n<li>Coroutine dispatchers<\/li>\n\n\n\n<li>Main-safe suspend functions<\/li>\n\n\n\n<li>Flow performance optimization<\/li>\n\n\n\n<li>StateFlow and SharedFlow best practices<\/li>\n\n\n\n<li>Avoiding coroutine leaks<\/li>\n\n\n\n<li>Parallel execution with async()<\/li>\n\n\n\n<li>Common coroutine anti-patterns<\/li>\n\n\n\n<li>Production-ready MVVM architecture<\/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. What Is Structured Concurrency in Kotlin?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Structured concurrency is a fundamental principle of Kotlin Coroutines.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It ensures that coroutines are organized within a predictable parent-child hierarchy.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A parent coroutine manages the lifecycle of its child coroutines.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Basic Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>suspend fun loadDashboard() = coroutineScope {\n\n    launch {\n        loadUserProfile()\n    }\n\n    launch {\n        loadNotifications()\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Both child coroutines belong to the same coroutineScope.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The function does not complete until its child coroutines finish.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If a child fails with an unhandled exception, the normal coroutineScope failure behavior cancels its siblings and propagates the failure.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Predictable coroutine lifecycles<\/li>\n\n\n\n<li>Automatic cancellation propagation<\/li>\n\n\n\n<li>Easier exception management<\/li>\n\n\n\n<li>Reduced risk of leaked work<\/li>\n\n\n\n<li>Better concurrency control<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Prefer structured concurrency over launching independent coroutines without a clearly defined owner.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">2. Understanding CoroutineScope<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">CoroutineScope defines the context in which coroutines execute.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It includes a CoroutineContext that commonly contains a Job and a dispatcher.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>val scope = CoroutineScope(\n    SupervisorJob() + Dispatchers.Default\n)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This creates a scope with a SupervisorJob and the Default dispatcher.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Creating a CoroutineScope also creates responsibility for managing its lifecycle.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If you own the scope, you must determine when it should be cancelled.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class DataProcessor {\n\n    private val scope = CoroutineScope(\n        SupervisorJob() + Dispatchers.Default\n    )\n\n    fun startProcessing() {\n\n        scope.launch {\n            processData()\n        }\n    }\n\n    fun close() {\n        scope.cancel()\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid creating unmanaged CoroutineScopes inside repositories or utility classes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Prefer receiving a CoroutineScope from a component that owns the required lifetime.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">3. Avoid GlobalScope in Android Applications<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">GlobalScope launches coroutines that are not tied to a normal application component&#8217;s lifecycle.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Not Recommended<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>GlobalScope.launch {\n    fetchUserData()\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Problems<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Work may continue after the screen disappears.<\/li>\n\n\n\n<li>Cancellation is difficult to coordinate.<\/li>\n\n\n\n<li>Errors can become harder to manage.<\/li>\n\n\n\n<li>Testing becomes more complicated.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Recommended<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class UserViewModel(\n    private val repository: UserRepository\n) : ViewModel() {\n\n    fun loadUser() {\n\n        viewModelScope.launch {\n            repository.getUser()\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\">viewModelScope is cancelled when the ViewModel is cleared.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This makes it suitable for ViewModel-owned operations.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">If work must continue after the ViewModel is destroyed, consider a longer-lived application-owned scope or WorkManager, depending on the work&#8217;s requirements.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">4. Use viewModelScope for ViewModel Operations<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">viewModelScope is one of the most commonly used coroutine scopes in modern Android development.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class ProductViewModel(\n    private val repository: ProductRepository\n) : ViewModel() {\n\n    private val _products =\n        MutableStateFlow&lt;List&lt;Product&gt;&gt;(emptyList())\n\n    val products = _products.asStateFlow()\n\n    fun loadProducts() {\n\n        viewModelScope.launch {\n\n            val result = repository.getProducts()\n\n            _products.value = result\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 coroutine belongs to the ViewModel.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When the ViewModel is cleared, its scope is cancelled.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Lifecycle-aware ownership<\/li>\n\n\n\n<li>Automatic scope cancellation<\/li>\n\n\n\n<li>Easy StateFlow integration<\/li>\n\n\n\n<li>Clean MVVM architecture<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use viewModelScope for work that should remain active while the ViewModel exists.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do not assume that viewModelScope work survives process death.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">5. Use lifecycleScope for Lifecycle-Owned Operations<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">lifecycleScope belongs to a LifecycleOwner, such as an Activity or Fragment.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class MainActivity : ComponentActivity() {\n\n    override fun onCreate(\n        savedInstanceState: Bundle?\n    ) {\n        super.onCreate(savedInstanceState)\n\n        lifecycleScope.launch {\n\n            performLifecycleOwnedOperation()\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 coroutine is cancelled when the lifecycle is destroyed.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">lifecycleScope does not automatically stop all work when an Activity enters the background.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For UI collection that should run only while the screen is visible, use repeatOnLifecycle().<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">6. Collect Kotlin Flow with repeatOnLifecycle()<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Collecting a Flow continuously while a screen is stopped can waste resources.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Android provides repeatOnLifecycle() for lifecycle-aware collection.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>lifecycleScope.launch {\n\n    repeatOnLifecycle(\n        Lifecycle.State.STARTED\n    ) {\n\n        viewModel.uiState.collect { state -&gt;\n\n            renderUi(state)\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\">Collection starts when the lifecycle reaches STARTED.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When the lifecycle falls below STARTED, the collection coroutine is cancelled.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Collection restarts when the lifecycle returns to STARTED.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use repeatOnLifecycle() for lifecycle-aware Flow collection in Activities and Fragments.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For StateFlow in Jetpack Compose, prefer collectAsStateWithLifecycle().<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">7. Collect StateFlow in Jetpack Compose<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Jetpack Compose integrates naturally with StateFlow.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@Composable\nfun ProfileScreen(\n    viewModel: ProfileViewModel = viewModel()\n) {\n\n    val uiState by viewModel.uiState\n        .collectAsStateWithLifecycle()\n\n    when (val state = uiState) {\n\n        is ProfileUiState.Loading -&gt; {\n            CircularProgressIndicator()\n        }\n\n        is ProfileUiState.Success -&gt; {\n            Text(state.name)\n        }\n\n        is ProfileUiState.Error -&gt; {\n            Text(state.message)\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\">collectAsStateWithLifecycle() observes StateFlow in a lifecycle-aware manner.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When the state changes, Compose updates the relevant UI.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Expose immutable StateFlow from the ViewModel and collect it in the UI layer.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">8. Understanding Coroutine Cancellation<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Coroutine cancellation allows asynchronous work to stop when it is no longer needed.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>val job = scope.launch {\n\n    repeat(100) { index -&gt;\n\n        delay(1000)\n\n        println(\"Processing $index\")\n    }\n}\n\njob.cancel()<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The coroutine performs repeated work.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When the Job is cancelled, the coroutine stops at a cancellation-aware suspension point.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Cancellation in Kotlin Coroutines is cooperative.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A coroutine performing CPU-intensive work without suspension or cancellation checks may continue running after cancellation is requested.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">9. Cooperative Cancellation with ensureActive()<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">For CPU-intensive loops, explicitly check cancellation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>suspend fun processLargeDataset(\n    items: List&lt;Int&gt;\n) {\n\n    withContext(Dispatchers.Default) {\n\n        for (item in items) {\n\n            ensureActive()\n\n            processItem(item)\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\">ensureActive() checks whether the coroutine is still active.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If cancellation has been requested, it throws CancellationException.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">When to Use<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Large data processing<\/li>\n\n\n\n<li>Image processing<\/li>\n\n\n\n<li>Computational loops<\/li>\n\n\n\n<li>Long-running transformations<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use cancellation checks in long-running operations that do not naturally suspend.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">10. Never Swallow CancellationException<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">CancellationException is part of normal coroutine cancellation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Incorrect<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>try {\n\n    repository.loadData()\n\n} catch (exception: Exception) {\n\n    println(\"Error occurred\")\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This may accidentally swallow cancellation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Correct<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>try {\n\n    repository.loadData()\n\n} catch (exception: CancellationException) {\n\n    throw exception\n\n} catch (exception: Exception) {\n\n    println(\n        \"Error: ${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 separately.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Preserve cancellation throughout repository, ViewModel, and business logic layers.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">11. Understanding SupervisorJob<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Normally, an unhandled child failure in a regular Job hierarchy can cancel the parent and sibling coroutines.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">SupervisorJob changes this behavior for its direct children.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>val scope = CoroutineScope(\n    SupervisorJob() + Dispatchers.Default\n)\n\nscope.launch {\n\n    try {\n        throw IllegalStateException(\"Task failed\")\n    } catch (exception: Exception) {\n        println(\"Task A failed\")\n    }\n}\n\nscope.launch {\n\n    println(\"Task B continues\")\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The SupervisorJob allows sibling coroutines to operate independently when one child fails.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this example, Task A also handles its own exception.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">SupervisorJob does not automatically handle exceptions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Unhandled exceptions from launch coroutines still require an appropriate exception-handling strategy.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">12. coroutineScope vs supervisorScope<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Both functions create structured coroutine scopes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, their failure behavior differs.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">coroutineScope<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>suspend fun loadData() = coroutineScope {\n\n    launch {\n        loadProfile()\n    }\n\n    launch {\n        loadSettings()\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">An unhandled child failure cancels sibling work and causes the scope to fail.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">supervisorScope<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>suspend fun loadIndependentData() = supervisorScope {\n\n    launch {\n        try {\n            loadProfile()\n        } catch (exception: CancellationException) {\n            throw exception\n        } catch (exception: Exception) {\n            logError(exception)\n        }\n    }\n\n    launch {\n        try {\n            loadSettings()\n        } catch (exception: CancellationException) {\n            throw exception\n        } catch (exception: Exception) {\n            logError(exception)\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\">supervisorScope allows independent child failures without automatically cancelling siblings.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Each independent operation should still handle its own failures appropriately.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">When to Use<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use coroutineScope when all child operations form one combined task.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use supervisorScope when independent operations should not cancel one another.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">13. Choose the Correct Coroutine Dispatcher<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Kotlin provides dispatchers for different types of work.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Dispatcher<\/th><th>Recommended Use<\/th><\/tr><tr><td>Dispatchers.Main<\/td><td>UI-related work<\/td><\/tr><tr><td>Dispatchers.IO<\/td><td>Blocking I\/O operations<\/td><\/tr><tr><td>Dispatchers.Default<\/td><td>CPU-intensive operations<\/td><\/tr><tr><td>Dispatchers.Unconfined<\/td><td>Specialized cases; generally avoid in ordinary Android code<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Dispatchers.Main<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>viewModelScope.launch {\n\n    _uiState.value = UiState.Loading\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Dispatchers.IO<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>withContext(Dispatchers.IO) {\n\n    readLargeFile()\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Dispatchers.Default<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>withContext(Dispatchers.Default) {\n\n    calculateComplexResult()\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Many modern suspend APIs already manage their own threading.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, Retrofit suspend functions and Room suspend DAO methods are designed to avoid blocking the main thread.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do not wrap every suspend call in Dispatchers.IO unnecessarily.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">14. Make Suspend Functions Main-Safe<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A main-safe suspend function can be called from the main thread without blocking it.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class FileRepository(\n    private val ioDispatcher: CoroutineDispatcher\n) {\n\n    suspend fun readFile(): String {\n\n        return withContext(ioDispatcher) {\n\n            File(\"sample.txt\").readText()\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 repository controls the dispatcher required for blocking file access.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel does not need to know how the repository performs the operation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Move blocking work away from the main thread inside the layer responsible for that work.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Inject dispatchers where appropriate to improve testability.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">15. Avoid Blocking the Main Thread<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Incorrect<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>viewModelScope.launch {\n\n    Thread.sleep(3000)\n\n    _uiState.value = UiState.Success\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Problem<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Thread.sleep() blocks the executing thread.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If executed on Dispatchers.Main, the UI becomes unresponsive.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Correct<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>viewModelScope.launch {\n\n    delay(3000)\n\n    _uiState.value = UiState.Success\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">delay() suspends the coroutine without blocking the thread.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use delay() for asynchronous waiting.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For blocking operations, use an appropriate dispatcher.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">16. Parallel Operations with async()<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Sometimes independent operations can run concurrently.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Sequential Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>suspend fun loadDashboard(): Dashboard {\n\n    val user = repository.getUser()\n\n    val notifications =\n        repository.getNotifications()\n\n    return Dashboard(\n        user,\n        notifications\n    )\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Parallel Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>suspend fun loadDashboard(): Dashboard =\n    coroutineScope {\n\n        val userDeferred = async {\n            repository.getUser()\n        }\n\n        val notificationsDeferred = async {\n            repository.getNotifications()\n        }\n\n        Dashboard(\n            user = userDeferred.await(),\n            notifications = notificationsDeferred.await()\n        )\n    }<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Both operations start concurrently.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The function waits for both results.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Parallel execution may reduce total waiting time when operations are independent.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use async() when you need a result.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use launch() when you need to start a coroutine without returning a value directly.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid unnecessary parallelism when operations are dependent or share constrained resources.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">17. Avoid Excessive Coroutine Creation<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Coroutines are lightweight, but they are not free.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Launching thousands of coroutines unnecessarily can increase scheduling overhead and resource usage.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>coroutineScope {\n\n    items.forEach { item -&gt;\n\n        launch {\n            processItem(item)\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This can be appropriate for a small collection.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For very large collections, uncontrolled concurrency may overwhelm a database, server, or device.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Better Approach: Limit Concurrency<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>suspend fun processItems(\n    items: List&lt;Item&gt;\n) = coroutineScope {\n\n    val semaphore = Semaphore(4)\n\n    items.map { item -&gt;\n\n        async {\n\n            semaphore.withPermit {\n                processItem(item)\n            }\n        }\n\n    }.awaitAll()\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The semaphore limits concurrent processing to four operations.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Choose concurrency limits based on the workload and available resources.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">18. StateFlow Best Practices<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">StateFlow is designed to represent observable state.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Recommended Pattern<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class SettingsViewModel : ViewModel() {\n\n    private val _uiState =\n        MutableStateFlow(SettingsUiState())\n\n    val uiState: StateFlow&lt;SettingsUiState&gt; =\n        _uiState.asStateFlow()\n\n    fun updateDarkMode(enabled: Boolean) {\n\n        _uiState.update { current -&gt;\n\n            current.copy(\n                darkModeEnabled = enabled\n            )\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practices<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Keep MutableStateFlow private.<\/li>\n\n\n\n<li>Expose read-only StateFlow.<\/li>\n\n\n\n<li>Prefer immutable UI state models.<\/li>\n\n\n\n<li>Use update() for atomic state transformations.<\/li>\n\n\n\n<li>Avoid exposing mutable collections.<\/li>\n\n\n\n<li>Keep state ownership clear.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">StateFlow uses equality-based conflation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Emitting an equal value does not produce a new observable state update.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">19. SharedFlow Best Practices<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">SharedFlow broadcasts values to active subscribers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class EventViewModel : ViewModel() {\n\n    private val _events =\n        MutableSharedFlow&lt;String&gt;()\n\n    val events: SharedFlow&lt;String&gt; =\n        _events.asSharedFlow()\n\n    fun sendEvent(message: String) {\n\n        viewModelScope.launch {\n\n            _events.emit(message)\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practices<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use SharedFlow for appropriate broadcast streams.<\/li>\n\n\n\n<li>Understand replay behavior.<\/li>\n\n\n\n<li>Configure buffering intentionally.<\/li>\n\n\n\n<li>Consider subscriber lifecycle.<\/li>\n\n\n\n<li>Do not assume every event is delivered.<\/li>\n\n\n\n<li>Avoid using SharedFlow as persistent storage.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For important UI outcomes that must survive lifecycle changes, represent the outcome in UI state or persistent storage.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">20. Optimize Flow Collection<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Repeated Flow collection can restart expensive upstream operations.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>val productsFlow = repository.observeProducts()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">If the Flow is cold, each collector may start a new upstream operation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Solution: stateIn()<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>val products = repository.observeProducts()\n    .stateIn(\n        scope = viewModelScope,\n        started = SharingStarted.WhileSubscribed(5000),\n        initialValue = emptyList()\n    )<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">stateIn() converts a Flow into StateFlow and shares its upstream collection.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Shared upstream work<\/li>\n\n\n\n<li>Observable latest state<\/li>\n\n\n\n<li>Better integration with Compose<\/li>\n\n\n\n<li>Reduced duplicate collection work<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use stateIn() when a cold Flow should be shared as observable state.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">21. Use shareIn() for Shared Streams<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The shareIn() operator converts a cold Flow into SharedFlow.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>val sharedUpdates = repository.observeUpdates()\n    .shareIn(\n        scope = viewModelScope,\n        started = SharingStarted.WhileSubscribed(5000),\n        replay = 0\n    )<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Multiple collectors share the same upstream stream.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">When to Use<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Shared real-time updates<\/li>\n\n\n\n<li>Multiple observers of one data source<\/li>\n\n\n\n<li>Expensive upstream operations<\/li>\n\n\n\n<li>Application event streams<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Choose a scope that matches the required lifetime of the shared stream.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">22. Avoid Unnecessary Flow Operators<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Flow operators are useful, but excessive transformations can make pipelines harder to understand.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>repository.observeProducts()\n    .map { products -&gt;\n        products.filter { it.isAvailable }\n    }\n    .map { products -&gt;\n        products.sortedBy { it.name }\n    }<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Alternative<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>repository.observeProducts()\n    .map { products -&gt;\n\n        products\n            .filter { it.isAvailable }\n            .sortedBy { it.name }\n    }<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Combining related transformations can improve readability.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Do not assume fewer operators always produce meaningful performance gains.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Measure performance before making complex optimizations.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">23. Use distinctUntilChanged() Appropriately<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">distinctUntilChanged() prevents consecutive equal emissions from continuing downstream.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>repository.observeSearchQuery()\n    .distinctUntilChanged()\n    .collect { query -&gt;\n\n        searchProducts(query)\n    }<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">If the same query is emitted repeatedly, duplicate values are filtered.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">StateFlow already performs equality-based conflation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Applying distinctUntilChanged() directly to StateFlow does not provide additional behavior.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">24. Use debounce() for Search Inputs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Search interfaces often receive rapid input changes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Calling an API for every keystroke can generate unnecessary requests.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>searchQuery\n    .debounce(300)\n    .distinctUntilChanged()\n    .collectLatest { query -&gt;\n\n        searchRepository.search(query)\n    }<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">debounce() waits for a quiet period.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">distinctUntilChanged() avoids repeated equal queries.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">collectLatest() cancels the previous collection action when a new value arrives.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use debounce() when waiting briefly for input stability improves the 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\">25. Understanding collectLatest()<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">collectLatest() cancels processing of the previous value when a newer value arrives.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>searchQuery.collectLatest { query -&gt;\n\n    val results = repository.search(query)\n\n    displayResults(results)\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">If a new query arrives before the previous search finishes, the previous collection action is cancelled.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Cancellation must be respected by the underlying work.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Blocking or non-cooperative operations may not stop immediately.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">26. Avoid Duplicate Network Requests<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A common mistake is starting the same network operation from multiple UI lifecycle events.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example Problem<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@Composable\nfun ProductScreen(\n    viewModel: ProductViewModel\n) {\n\n    viewModel.loadProducts()\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Why Is This Wrong?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Composable functions can recompose many times.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Calling loadProducts() directly in the composable body may trigger repeated requests.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Better Approach<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@Composable\nfun ProductScreen(\n    viewModel: ProductViewModel\n) {\n\n    LaunchedEffect(viewModel) {\n\n        viewModel.loadProducts()\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">LaunchedEffect runs when it enters composition and restarts when its keys change.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For screen data that should load once per ViewModel instance, consider starting the operation in the ViewModel&#8217;s init block.<\/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: Production-Ready Dashboard with Coroutines &amp; Flow<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Now let&#8217;s build a small dashboard that demonstrates several best practices together.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Features<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Parallel data loading<\/li>\n\n\n\n<li>Structured concurrency<\/li>\n\n\n\n<li>ViewModel-owned work<\/li>\n\n\n\n<li>Cancellation support<\/li>\n\n\n\n<li>StateFlow UI state<\/li>\n\n\n\n<li>Error handling<\/li>\n\n\n\n<li>Jetpack Compose integration<\/li>\n\n\n\n<li>Manual refresh<\/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>StateFlow<\/li>\n\n\n\n<li>ViewModel<\/li>\n\n\n\n<li>Jetpack Compose<\/li>\n\n\n\n<li>Material 3<\/li>\n\n\n\n<li>MVVM<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">For simplicity, we&#8217;ll simulate repository operations.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">27. Create the Dashboard Models<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>data class UserProfile(\n    val name: String,\n    val email: String\n)\n\ndata class DashboardData(\n    val user: UserProfile,\n    val notificationCount: Int\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">UserProfile stores basic user information.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">DashboardData combines the profile and notification count.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">28. Create the Dashboard Repository<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>class DashboardRepository {\n\n    suspend fun getUserProfile(): UserProfile {\n\n        delay(800)\n\n        return UserProfile(\n            name = \"Android Developer\",\n            email = \"developer@example.com\"\n        )\n    }\n\n    suspend fun getNotificationCount(): Int {\n\n        delay(1200)\n\n        return 8\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Both functions simulate asynchronous operations.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Because they use delay(), they do not block a thread while waiting.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">29. Create Dashboard UI State<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>sealed interface DashboardUiState {\n\n    data object Loading : DashboardUiState\n\n    data class Success(\n        val data: DashboardData\n    ) : DashboardUiState\n\n    data class Error(\n        val message: String\n    ) : DashboardUiState\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The UI can display loading, success, or error states.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">30. Create the Dashboard ViewModel<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>class DashboardViewModel(\n    private val repository: DashboardRepository\n) : ViewModel() {\n\n    private val _uiState =\n        MutableStateFlow&lt;DashboardUiState&gt;(\n            DashboardUiState.Loading\n        )\n\n    val uiState: StateFlow&lt;DashboardUiState&gt; =\n        _uiState.asStateFlow()\n\n    private var refreshJob: Job? = null\n\n    init {\n        refresh()\n    }\n\n    fun refresh() {\n\n        refreshJob?.cancel()\n\n        refreshJob = viewModelScope.launch {\n\n            _uiState.value = DashboardUiState.Loading\n\n            try {\n\n                val dashboard = coroutineScope {\n\n                    val userDeferred = async {\n                        repository.getUserProfile()\n                    }\n\n                    val notificationsDeferred = async {\n                        repository.getNotificationCount()\n                    }\n\n                    DashboardData(\n                        user = userDeferred.await(),\n                        notificationCount =\n                            notificationsDeferred.await()\n                    )\n                }\n\n                _uiState.value =\n                    DashboardUiState.Success(dashboard)\n\n            } catch (exception: CancellationException) {\n\n                throw exception\n\n            } catch (exception: Exception) {\n\n                _uiState.value =\n                    DashboardUiState.Error(\n                        \"Unable to load dashboard\"\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 ViewModel starts loading when created.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The profile and notification operations run concurrently.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">coroutineScope waits for both results.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If both succeed, the ViewModel publishes Success.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If an operation fails, the ViewModel publishes Error.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When refresh() is called again, the previous refresh job is cancelled.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Structured concurrency<\/li>\n\n\n\n<li>Predictable cancellation<\/li>\n\n\n\n<li>Parallel independent operations<\/li>\n\n\n\n<li>Explicit UI state<\/li>\n\n\n\n<li>ViewModel lifecycle ownership<\/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\">31. Create the Jetpack Compose Dashboard Screen<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>@Composable\nfun DashboardScreen(\n    viewModel: DashboardViewModel\n) {\n\n    val uiState by viewModel.uiState\n        .collectAsStateWithLifecycle()\n\n    Column(\n        modifier = Modifier\n            .fillMaxSize()\n            .padding(24.dp),\n        verticalArrangement =\n            Arrangement.spacedBy(16.dp)\n    ) {\n\n        Text(\n            text = \"Developer Dashboard\",\n            style = MaterialTheme.typography.headlineMedium\n        )\n\n        when (val state = uiState) {\n\n            DashboardUiState.Loading -&gt; {\n\n                CircularProgressIndicator()\n            }\n\n            is DashboardUiState.Success -&gt; {\n\n                Text(\n                    text = \"Welcome, ${state.data.user.name}\",\n                    style = MaterialTheme.typography.titleLarge\n                )\n\n                Text(\n                    text = state.data.user.email\n                )\n\n                Card(\n                    modifier = Modifier.fillMaxWidth()\n                ) {\n\n                    Column(\n                        modifier = Modifier.padding(16.dp)\n                    ) {\n\n                        Text(\n                            text = \"Notifications\",\n                            style = MaterialTheme.typography.titleMedium\n                        )\n\n                        Text(\n                            text = \"${state.data.notificationCount} unread\"\n                        )\n                    }\n                }\n\n                Button(\n                    onClick = {\n                        viewModel.refresh()\n                    }\n                ) {\n\n                    Text(\"Refresh Dashboard\")\n                }\n            }\n\n            is DashboardUiState.Error -&gt; {\n\n                Text(\n                    text = state.message,\n                    color = MaterialTheme.colorScheme.error\n                )\n\n                Button(\n                    onClick = {\n                        viewModel.refresh()\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 screen observes StateFlow using collectAsStateWithLifecycle().<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The UI automatically updates when the ViewModel publishes a new state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The Refresh button starts a new request.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The Retry button allows recovery after a failure.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">32. Create the MainActivity<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">For this standalone tutorial, we can construct the repository and ViewModel through a ViewModel factory.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class MainActivity : ComponentActivity() {\n\n    override fun onCreate(\n        savedInstanceState: Bundle?\n    ) {\n\n        super.onCreate(savedInstanceState)\n\n        setContent {\n\n            MaterialTheme {\n\n                val viewModel: DashboardViewModel =\n                    viewModel(\n                        factory = DashboardViewModelFactory(\n                            DashboardRepository()\n                        )\n                    )\n\n                DashboardScreen(\n                    viewModel = viewModel\n                )\n            }\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">ViewModel Factory<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class DashboardViewModelFactory(\n    private val repository: DashboardRepository\n) : ViewModelProvider.Factory {\n\n    override fun &lt;T : ViewModel&gt; create(\n        modelClass: Class&lt;T&gt;\n    ): T {\n\n        if (\n            modelClass.isAssignableFrom(\n                DashboardViewModel::class.java\n            )\n        ) {\n\n            @Suppress(\"UNCHECKED_CAST\")\n            return DashboardViewModel(repository) as T\n        }\n\n        throw IllegalArgumentException(\n            \"Unknown ViewModel class\"\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 factory creates DashboardViewModel with its repository dependency.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In larger production applications, Hilt can manage dependency injection automatically.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">33. Expected UI \u2014 Loading<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>+--------------------------------+\n|                                |\n|      Developer Dashboard       |\n|                                |\n|              \u25cb                 |\n|                                |\n|       Loading dashboard...     |\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\">34. Expected UI \u2014 Success<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>+--------------------------------+\n|                                |\n|      Developer Dashboard       |\n|                                |\n| Welcome, Android Developer     |\n|                                |\n| developer@example.com          |\n|                                |\n| +----------------------------+ |\n| | Notifications              | |\n| |                            | |\n| | 8 unread                   | |\n| +----------------------------+ |\n|                                |\n|      &#91; Refresh Dashboard ]     |\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\">35. Expected UI \u2014 Error<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>+--------------------------------+\n|                                |\n|      Developer Dashboard       |\n|                                |\n|   Unable to load dashboard     |\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\">36. How the Application Works<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Step 1: ViewModel Initializes<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel starts loading dashboard data.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 2: StateFlow Publishes Loading<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The Compose screen displays a progress indicator.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 3: Two Operations Start Concurrently<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The repository loads the user profile and notification count.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 4: Structured Concurrency Manages Both Tasks<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">coroutineScope waits for both operations to complete.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 5: ViewModel Publishes Success<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The combined DashboardData is stored in StateFlow.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 6: Compose Updates the UI<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The screen displays the profile and notifications.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 7: User Refreshes<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The previous refresh job is cancelled if necessary.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A new refresh operation begins.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This architecture demonstrates lifecycle ownership, structured concurrency, and predictable UI state management.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">37. Common Kotlin Coroutine Anti-Patterns<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Anti-Pattern 1: Using GlobalScope<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid unmanaged global coroutines for ordinary screen operations.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Anti-Pattern 2: Blocking Dispatchers.Main<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Do not perform blocking file or network operations on the main thread.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Anti-Pattern 3: Ignoring Cancellation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Preserve CancellationException and use cooperative cancellation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Anti-Pattern 4: Launching Coroutines Inside Every Recomposition<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use ViewModel, LaunchedEffect, or appropriate event handlers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Anti-Pattern 5: Creating Unmanaged CoroutineScopes<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Every custom CoroutineScope should have a clear owner and cancellation strategy.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Anti-Pattern 6: Using async() Without Awaiting Results<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use async() when results are needed and await them within structured concurrency.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Anti-Pattern 7: Unlimited Parallelism<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Limit concurrency when working with large datasets or constrained resources.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Anti-Pattern 8: Retrying Every Failure<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Retry only appropriate failures with bounded policies.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Anti-Pattern 9: Collecting Expensive Cold Flows Multiple Times<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Consider stateIn() or shareIn() when upstream sharing is appropriate.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Anti-Pattern 10: Assuming Every Flow Emission Is Delivered<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Understand StateFlow conflation and SharedFlow replay and buffering behavior.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">38. Production Best Practices Checklist<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Before releasing an Android application, review these practices:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use structured concurrency.<\/li>\n\n\n\n<li>Keep coroutine ownership explicit.<\/li>\n\n\n\n<li>Prefer viewModelScope for ViewModel operations.<\/li>\n\n\n\n<li>Use lifecycle-aware Flow collection.<\/li>\n\n\n\n<li>Avoid GlobalScope for ordinary app work.<\/li>\n\n\n\n<li>Preserve coroutine cancellation.<\/li>\n\n\n\n<li>Use ensureActive() in long CPU-intensive loops.<\/li>\n\n\n\n<li>Select dispatchers based on workload.<\/li>\n\n\n\n<li>Keep suspend functions main-safe.<\/li>\n\n\n\n<li>Avoid blocking the main thread.<\/li>\n\n\n\n<li>Use async() for independent concurrent operations.<\/li>\n\n\n\n<li>Limit excessive parallelism.<\/li>\n\n\n\n<li>Handle exceptions at meaningful boundaries.<\/li>\n\n\n\n<li>Use StateFlow for observable UI state.<\/li>\n\n\n\n<li>Use SharedFlow for appropriate broadcast streams.<\/li>\n\n\n\n<li>Share expensive upstream Flows when needed.<\/li>\n\n\n\n<li>Avoid duplicate network requests.<\/li>\n\n\n\n<li>Use debounce() for suitable search interactions.<\/li>\n\n\n\n<li>Use collectLatest() when newer work should replace older work.<\/li>\n\n\n\n<li>Test cancellation, errors, and concurrency behavior.<\/li>\n\n\n\n<li>Measure performance before optimizing.<\/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\">39. Kotlin Coroutines &amp; Flow 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>coroutineScope()<\/td><td>Structured child coroutine execution<\/td><\/tr><tr><td>supervisorScope()<\/td><td>Independent child failure handling<\/td><\/tr><tr><td>CoroutineScope<\/td><td>Owns coroutine execution context<\/td><\/tr><tr><td>viewModelScope<\/td><td>ViewModel-owned coroutine scope<\/td><\/tr><tr><td>lifecycleScope<\/td><td>LifecycleOwner-owned coroutine scope<\/td><\/tr><tr><td>repeatOnLifecycle()<\/td><td>Lifecycle-aware Flow collection<\/td><\/tr><tr><td>launch()<\/td><td>Start a coroutine<\/td><\/tr><tr><td>async()<\/td><td>Start coroutine returning Deferred<\/td><\/tr><tr><td>await()<\/td><td>Await Deferred result<\/td><\/tr><tr><td>withContext()<\/td><td>Execute work in another context<\/td><\/tr><tr><td>delay()<\/td><td>Non-blocking suspension<\/td><\/tr><tr><td>ensureActive()<\/td><td>Check cancellation<\/td><\/tr><tr><td>SupervisorJob<\/td><td>Isolate direct child failures<\/td><\/tr><tr><td>StateFlow<\/td><td>Observable current state<\/td><\/tr><tr><td>SharedFlow<\/td><td>Shared broadcast stream<\/td><\/tr><tr><td>stateIn()<\/td><td>Convert Flow to StateFlow<\/td><\/tr><tr><td>shareIn()<\/td><td>Convert Flow to SharedFlow<\/td><\/tr><tr><td>debounce()<\/td><td>Delay emissions until input stabilizes<\/td><\/tr><tr><td>collectLatest()<\/td><td>Cancel previous processing on new emission<\/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\">40. 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: Structured Concurrency<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Create two child coroutines inside coroutineScope().<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 2: Cancellation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Start a repeating coroutine and cancel it after a short delay.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 3: ensureActive()<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Create a CPU-intensive loop that checks cancellation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 4: SupervisorJob<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Demonstrate independent child coroutine failures.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 5: Dispatchers<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Move a blocking file operation to Dispatchers.IO.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 6: Parallel Operations<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Load two independent datasets using async().<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 7: StateFlow<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Create a ViewModel that exposes immutable UI state.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 8: SharedFlow<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Create a shared event stream with multiple collectors.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 9: Flow Optimization<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use stateIn() to share a cold Flow inside a ViewModel.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 10: Dashboard Mini-Project<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Build the complete dashboard example from this tutorial.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">41. Frequently Asked Questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">What is structured concurrency in Kotlin?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Structured concurrency organizes coroutines into parent-child relationships so their lifecycles and failures can be managed predictably.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is viewModelScope?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">viewModelScope is a CoroutineScope tied to an Android ViewModel.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is cancelled when the ViewModel is cleared.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is lifecycleScope?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">lifecycleScope is a CoroutineScope associated with an Android LifecycleOwner.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is the difference between coroutineScope and supervisorScope?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">coroutineScope propagates unhandled child failures and cancels sibling work.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">supervisorScope allows direct child failures to be isolated.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is SupervisorJob?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">SupervisorJob is a Job that prevents a failing direct child from automatically cancelling its siblings.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why should GlobalScope be avoided?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">GlobalScope is not tied to a normal component lifecycle, making ownership, cancellation, and testing harder.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is cooperative cancellation?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Cooperative cancellation means coroutine code must reach cancellation-aware suspension points or explicitly check its cancellation state.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is the difference between Dispatchers.IO and Dispatchers.Default?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Dispatchers.IO is intended for blocking I\/O work.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Dispatchers.Default is intended for CPU-intensive work.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is the difference between launch and async?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">launch starts a coroutine and returns a Job.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">async starts a coroutine and returns a Deferred result.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How can I improve Kotlin Flow performance?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use lifecycle-aware collection, avoid unnecessary duplicate upstream work, share expensive Flows when appropriate, and measure performance before optimizing.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Should I use StateFlow or SharedFlow?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use StateFlow for current observable state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use SharedFlow when broadcasting values to active subscribers is appropriate.<\/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 explored:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Structured concurrency<\/li>\n\n\n\n<li>CoroutineScope ownership<\/li>\n\n\n\n<li>viewModelScope and lifecycleScope<\/li>\n\n\n\n<li>Lifecycle-aware Flow collection<\/li>\n\n\n\n<li>Coroutine cancellation<\/li>\n\n\n\n<li>Cooperative cancellation<\/li>\n\n\n\n<li>SupervisorJob<\/li>\n\n\n\n<li>coroutineScope vs supervisorScope<\/li>\n\n\n\n<li>Coroutine dispatchers<\/li>\n\n\n\n<li>Main-safe suspend functions<\/li>\n\n\n\n<li>Avoiding main-thread blocking<\/li>\n\n\n\n<li>Parallel operations with async()<\/li>\n\n\n\n<li>Concurrency limits<\/li>\n\n\n\n<li>StateFlow best practices<\/li>\n\n\n\n<li>SharedFlow best practices<\/li>\n\n\n\n<li>stateIn and shareIn<\/li>\n\n\n\n<li>Flow performance optimization<\/li>\n\n\n\n<li>Avoiding duplicate network requests<\/li>\n\n\n\n<li>Production-ready ViewModel architecture<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Kotlin Coroutines and Flow make asynchronous Android development more manageable, but correct lifecycle ownership and cancellation behavior are essential.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By applying these best practices, developers can build Android applications that are more responsive, maintainable, testable, and reliable.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">These concepts provide a strong foundation for advanced Android architecture, dependency injection, networking, database integration, and production performance optimization.<\/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 begin exploring modern Android application architecture.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Article 38 \u2014 MVVM Architecture in Android with Kotlin &amp; Jetpack Compose: Complete Beginner-to-Advanced Guide<\/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>What software architecture means in Android<\/li>\n\n\n\n<li>Why MVVM is widely used<\/li>\n\n\n\n<li>Model, View, and ViewModel responsibilities<\/li>\n\n\n\n<li>UI state management<\/li>\n\n\n\n<li>Unidirectional Data Flow<\/li>\n\n\n\n<li>Repository pattern<\/li>\n\n\n\n<li>StateFlow integration<\/li>\n\n\n\n<li>ViewModel lifecycle<\/li>\n\n\n\n<li>Dependency injection concepts<\/li>\n\n\n\n<li>Jetpack Compose integration<\/li>\n\n\n\n<li>Practical MVVM Android mini-project<\/li>\n\n\n\n<li>Common architecture mistakes<\/li>\n\n\n\n<li>Production best practices<\/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>Learn production-ready Kotlin Coroutines and Flow best practices for Android. Master structured concurrency, cancellation, CoroutineScope ownership, dispatchers, exception handling, and performance optimization.<\/p>\n","protected":false},"author":1,"featured_media":173,"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-172","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\/172","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=172"}],"version-history":[{"count":1,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/172\/revisions"}],"predecessor-version":[{"id":174,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/172\/revisions\/174"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/media\/173"}],"wp:attachment":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/media?parent=172"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/categories?post=172"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/tags?post=172"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}