{"id":163,"date":"2026-10-18T11:50:00","date_gmt":"2026-10-18T11:50:00","guid":{"rendered":"https:\/\/moiks.com\/blog\/?p=163"},"modified":"2026-11-06T08:48:31","modified_gmt":"2026-11-06T08:48:31","slug":"kotlin-sharedflow-in-android-events-replay-buffering-jetpack-compose","status":"publish","type":"post","link":"https:\/\/moiks.com\/blog\/kotlin-sharedflow-in-android-events-replay-buffering-jetpack-compose\/","title":{"rendered":"Kotlin SharedFlow in Android: Events, Replay, Buffering &#038; Jetpack Compose"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Modern Android applications frequently need to communicate events between different parts of an application.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A download starts or finishes.<\/li>\n\n\n\n<li>A user completes an action.<\/li>\n\n\n\n<li>A background operation reports an event.<\/li>\n\n\n\n<li>Multiple components need to receive the same update.<\/li>\n\n\n\n<li>A message must be broadcast to active subscribers.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Kotlin provides <strong>SharedFlow<\/strong>, a powerful coroutine-based API for broadcasting values to multiple collectors.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">SharedFlow is part of Kotlin Flow and works naturally with Kotlin Coroutines, ViewModel, and Jetpack Compose.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In our previous tutorial, we learned how StateFlow manages observable UI state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Now we&#8217;ll explore how SharedFlow works, how it differs from StateFlow, and when it should be used in real Android applications.<\/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>What Kotlin SharedFlow is<\/li>\n\n\n\n<li>How hot streams work<\/li>\n\n\n\n<li>MutableSharedFlow vs SharedFlow<\/li>\n\n\n\n<li>How to emit and collect values<\/li>\n\n\n\n<li>emit() vs tryEmit()<\/li>\n\n\n\n<li>Multiple collectors<\/li>\n\n\n\n<li>Replay cache<\/li>\n\n\n\n<li>Buffering and overflow strategies<\/li>\n\n\n\n<li>subscriptionCount<\/li>\n\n\n\n<li>SharedFlow vs StateFlow<\/li>\n\n\n\n<li>SharedFlow vs Channel<\/li>\n\n\n\n<li>shareIn()<\/li>\n\n\n\n<li>ViewModel integration<\/li>\n\n\n\n<li>Lifecycle-aware collection<\/li>\n\n\n\n<li>SharedFlow with Jetpack Compose<\/li>\n\n\n\n<li>Common event delivery problems<\/li>\n\n\n\n<li>Practical Android mini-project<\/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. What Is Kotlin SharedFlow?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">SharedFlow is a hot Flow that broadcasts emitted values to its subscribers.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Unlike a standard cold Flow, SharedFlow does not restart a separate producer for every collector.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Basic Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>val events = MutableSharedFlow&lt;String&gt;()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This creates a mutable SharedFlow that can broadcast String values.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We can emit a value:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>events.emit(\"Download started\")<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Collectors can receive the event:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>events.collect { event -&gt;\n    println(event)\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Key Characteristics<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">SharedFlow:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Is a hot stream<\/li>\n\n\n\n<li>Supports multiple subscribers<\/li>\n\n\n\n<li>Does not require an initial value<\/li>\n\n\n\n<li>Supports configurable replay<\/li>\n\n\n\n<li>Supports optional buffering<\/li>\n\n\n\n<li>Supports different overflow strategies<\/li>\n\n\n\n<li>Does not complete normally<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A default MutableSharedFlow has no replay cache.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If an event is emitted while no subscribers are active, it will not be delivered to future subscribers.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This behavior is important when designing Android UI events.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">2. Why Use SharedFlow in Android?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Consider an application that broadcasts download status messages.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Different components may want to observe these messages:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A download screen<\/li>\n\n\n\n<li>A logging component<\/li>\n\n\n\n<li>A status monitor<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">SharedFlow allows active collectors to observe the same stream.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Basic Architecture<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Background Operation\n        |\n        v\nRepository \/ Event Source\n        |\n        v\nMutableSharedFlow\n        |\n        v\nSharedFlow\n        |\n        +----&gt; Collector A\n        |\n        +----&gt; Collector B\n        |\n        +----&gt; Collector C<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Common Use Cases<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">SharedFlow can be useful for:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Broadcasting application events<\/li>\n\n\n\n<li>Sharing a stream among multiple collectors<\/li>\n\n\n\n<li>Observing download milestones<\/li>\n\n\n\n<li>Distributing real-time notifications<\/li>\n\n\n\n<li>Sharing updates from a long-lived data source<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">However, SharedFlow is not automatically a reliable event queue.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For actions that must survive screen recreation or process death, persistent state may be more appropriate.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">3. Add Kotlin SharedFlow Dependencies<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">SharedFlow is included in the Kotlin Coroutines library.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In an Android project, add the appropriate dependency.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">build.gradle.kts<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>dependencies {\n\n    implementation(\n        \"org.jetbrains.kotlinx:kotlinx-coroutines-android:&lt;version&gt;\"\n    )\n\n    implementation(\n        \"androidx.lifecycle:lifecycle-viewmodel-ktx:&lt;version&gt;\"\n    )\n\n    implementation(\n        \"androidx.lifecycle:lifecycle-runtime-ktx:&lt;version&gt;\"\n    )\n\n    implementation(\n        \"androidx.lifecycle:lifecycle-runtime-compose:&lt;version&gt;\"\n    )\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Replace the placeholders with compatible stable versions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If your project uses a Gradle Version Catalog, manage dependencies through <code>libs.versions.toml<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Common Imports<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import kotlinx.coroutines.flow.MutableSharedFlow\nimport kotlinx.coroutines.flow.SharedFlow\nimport kotlinx.coroutines.flow.asSharedFlow\nimport kotlinx.coroutines.flow.collect\nimport kotlinx.coroutines.launch<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">4. MutableSharedFlow vs SharedFlow<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Kotlin provides two closely related interfaces.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">MutableSharedFlow<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">MutableSharedFlow allows values to be emitted.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>val events = MutableSharedFlow&lt;String&gt;()<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">SharedFlow<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">SharedFlow provides a read-only interface for collectors.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>val events: SharedFlow&lt;String&gt;<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Recommended ViewModel Pattern<\/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            _events.emit(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\">The ViewModel owns the mutable event stream.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Other components observe the public SharedFlow.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This prevents external components from emitting events directly.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Keep MutableSharedFlow private and expose SharedFlow publicly.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">5. Your First Complete SharedFlow Example<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s create a simple program that emits and collects events.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>fun main() = runBlocking {\n\n    val events = MutableSharedFlow&lt;String&gt;()\n\n    val collectorJob = launch {\n\n        events.collect { event -&gt;\n            println(\"Received: $event\")\n        }\n    }\n\n    events.subscriptionCount.first {\n        it &gt; 0\n    }\n\n    events.emit(\"Download started\")\n\n    events.emit(\"Download completed\")\n\n    collectorJob.cancelAndJoin()\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Expected Output<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Received: Download started\nReceived: Download completed<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">First, we create a MutableSharedFlow.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Next, we launch a collector.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We wait until a subscriber is registered.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Then we emit two events.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Finally, we cancel the collector.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why Wait for subscriptionCount?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A default SharedFlow does not replay past emissions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Without waiting for the collector to subscribe, the emitted events could be missed.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">SharedFlow collection normally continues until the collecting coroutine is cancelled.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">6. Understanding Hot Streams<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A hot stream exists independently of individual collectors.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">SharedFlow and StateFlow are both hot streams.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Cold Flow Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>val numbers = flow {\n\n    println(\"Producer started\")\n\n    emit(1)\n    emit(2)\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Each collector starts a new execution of the cold Flow.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Hot SharedFlow Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>val events = MutableSharedFlow&lt;Int&gt;()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The SharedFlow exists independently of whether any collector is active.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Multiple collectors can observe the same emissions.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Comparison<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Feature<\/th><th>Cold Flow<\/th><th>SharedFlow<\/th><\/tr><tr><td>Starts per collector<\/td><td>Usually yes<\/td><td>No<\/td><\/tr><tr><td>Shared emissions<\/td><td>Not by default<\/td><td>Yes<\/td><\/tr><tr><td>Replay<\/td><td>Depends on implementation<\/td><td>Configurable<\/td><\/tr><tr><td>Multiple subscribers<\/td><td>Yes<\/td><td>Yes<\/td><\/tr><tr><td>Typical purpose<\/td><td>Data pipeline<\/td><td>Broadcast stream<\/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\">7. Broadcasting Events to Multiple Collectors<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">SharedFlow supports multiple subscribers.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s create two collectors.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>fun main() = runBlocking {\n\n    val events = MutableSharedFlow&lt;String&gt;()\n\n    val collectorA = launch {\n\n        events.collect { event -&gt;\n            println(\"Collector A: $event\")\n        }\n    }\n\n    val collectorB = launch {\n\n        events.collect { event -&gt;\n            println(\"Collector B: $event\")\n        }\n    }\n\n    events.subscriptionCount.first {\n        it == 2\n    }\n\n    events.emit(\"New update available\")\n\n    collectorA.cancelAndJoin()\n    collectorB.cancelAndJoin()\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Expected Output<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Collector A: New update available\nCollector B: New update available<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Both collectors subscribe to the same SharedFlow.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When an event is emitted, both active collectors receive it.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Practical Uses<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Broadcasting status updates<\/li>\n\n\n\n<li>Multiple observers monitoring a shared service<\/li>\n\n\n\n<li>Application-wide notifications<\/li>\n\n\n\n<li>Logging and monitoring<\/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\">8. Understanding SharedFlow Replay<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Replay controls how many recent values are retained for new subscribers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>val events = MutableSharedFlow&lt;String&gt;(\n    replay = 2\n)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This SharedFlow retains the two most recent emitted values.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Complete Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>fun main() = runBlocking {\n\n    val events = MutableSharedFlow&lt;String&gt;(\n        replay = 2\n    )\n\n    events.emit(\"Event 1\")\n    events.emit(\"Event 2\")\n    events.emit(\"Event 3\")\n\n    println(events.replayCache)\n\n    events.take(2).collect {\n        println(\"Received: $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>&#91;Event 2, Event 3]\nReceived: Event 2\nReceived: Event 3<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The replay cache retains the two most recent values.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When a new collector subscribes, it immediately receives those values.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">When to Use Replay<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Replay can be useful when new subscribers should receive recent information.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Replay can also cause repeated event handling.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, replaying a navigation command after screen recreation could trigger navigation again.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Choose replay settings carefully.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">9. What Is replayCache?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>replayCache<\/code> property provides a snapshot of values currently retained for replay.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>val events = MutableSharedFlow&lt;Int&gt;(\n    replay = 3\n)\n\nevents.emit(10)\nevents.emit(20)\nevents.emit(30)\n\nprintln(events.replayCache)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Output<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;10, 20, 30]<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The replay cache contains recent emitted values up to the configured replay count.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Replay cache is not a persistent database.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Its contents exist only while the SharedFlow instance remains alive.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">10. SharedFlow Buffering<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">SharedFlow can maintain additional buffered values for active subscribers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>val events = MutableSharedFlow&lt;String&gt;(\n    replay = 0,\n    extraBufferCapacity = 5\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This configuration provides additional buffering capacity for active subscribers.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It can help producers continue temporarily when collectors are slower.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Parameters<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>replay<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Number of recent values retained for new subscribers.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>extraBufferCapacity<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Additional capacity beyond replay for slow active subscribers.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>onBufferOverflow<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Determines behavior when the buffer is full.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Extra buffer capacity does not store events for future subscribers when no subscribers are present.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">With no subscribers, only replay values are retained.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">11. SharedFlow Buffer Overflow Strategies<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">SharedFlow supports several overflow strategies.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">BufferOverflow.SUSPEND<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The producer suspends when necessary until buffer space becomes available.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>MutableSharedFlow&lt;Int&gt;(\n    replay = 1,\n    extraBufferCapacity = 2,\n    onBufferOverflow = BufferOverflow.SUSPEND\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">BufferOverflow.DROP_OLDEST<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The oldest buffered values are dropped when necessary to make room for newer values.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>MutableSharedFlow&lt;Int&gt;(\n    replay = 1,\n    extraBufferCapacity = 2,\n    onBufferOverflow = BufferOverflow.DROP_OLDEST\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">BufferOverflow.DROP_LATEST<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">New values are dropped when the buffer is full.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>MutableSharedFlow&lt;Int&gt;(\n    replay = 1,\n    extraBufferCapacity = 2,\n    onBufferOverflow = BufferOverflow.DROP_LATEST\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Comparison<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Strategy<\/th><th>Behavior<\/th><\/tr><tr><td>SUSPEND<\/td><td>Wait for available capacity<\/td><\/tr><tr><td>DROP_OLDEST<\/td><td>Discard oldest buffered values<\/td><\/tr><tr><td>DROP_LATEST<\/td><td>Discard new values when full<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Non-suspending overflow strategies require positive replay or extra buffer capacity.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Also, overflow occurs only when at least one subscriber is slow enough to create backpressure.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">12. emit() vs tryEmit()<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">MutableSharedFlow provides two common ways to emit values.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">emit()<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>events.emit(\"Download started\")<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The emit() function is a suspend function.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Depending on configuration and subscriber behavior, it may suspend.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">tryEmit()<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>val accepted = events.tryEmit(\n    \"Download started\"\n)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">tryEmit() is non-suspending.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It returns a Boolean indicating whether the value was accepted under the configured buffer behavior.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Comparison<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Feature<\/th><th>emit()<\/th><th>tryEmit()<\/th><\/tr><tr><td>Suspend function<\/td><td>Yes<\/td><td>No<\/td><\/tr><tr><td>May suspend<\/td><td>Yes<\/td><td>No<\/td><\/tr><tr><td>Returns Boolean<\/td><td>No<\/td><td>Yes<\/td><\/tr><tr><td>Typical use<\/td><td>Coroutine-based emission<\/td><td>Non-suspending emission attempt<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A successful tryEmit() call does not guarantee that a subscriber processed the value.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For a default unbuffered SharedFlow with no subscribers, tryEmit() can return true even though the event is discarded.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use emit() when suspension and backpressure are acceptable.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use tryEmit() only when non-suspending behavior fits the stream&#8217;s delivery requirements.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">13. Understanding subscriptionCount<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">MutableSharedFlow exposes the number of active subscribers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>val events = MutableSharedFlow&lt;String&gt;()\n\nevents.subscriptionCount.collect { count -&gt;\n\n    println(\"Active subscribers: $count\")\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">subscriptionCount is a StateFlow containing the current number of subscribers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Practical Uses<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Monitoring active collectors<\/li>\n\n\n\n<li>Starting work when subscribers exist<\/li>\n\n\n\n<li>Debugging event delivery<\/li>\n\n\n\n<li>Managing shared producers<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A subscription count is not a guarantee that an event will be handled successfully.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Subscribers may be cancelled or fail after registration.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">14. SharedFlow vs StateFlow<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Both SharedFlow and StateFlow are hot streams.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, they have different semantics.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Feature<\/th><th>SharedFlow<\/th><th>StateFlow<\/th><\/tr><tr><td>Initial value required<\/td><td>No<\/td><td>Yes<\/td><\/tr><tr><td>Current value property<\/td><td>No<\/td><td>Yes<\/td><\/tr><tr><td>Replay<\/td><td>Configurable<\/td><td>Latest value<\/td><\/tr><tr><td>Equality conflation<\/td><td>Not automatic<\/td><td>Yes<\/td><\/tr><tr><td>Buffering<\/td><td>Configurable<\/td><td>Conflated state<\/td><\/tr><tr><td>Typical use<\/td><td>Broadcasting values<\/td><td>Current state<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Use StateFlow For<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Screen UI state<\/li>\n\n\n\n<li>Loading indicators<\/li>\n\n\n\n<li>Selected tabs<\/li>\n\n\n\n<li>Form values<\/li>\n\n\n\n<li>User profiles<\/li>\n\n\n\n<li>Application settings<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Use SharedFlow For<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Broadcasting messages to active subscribers<\/li>\n\n\n\n<li>Shared event streams<\/li>\n\n\n\n<li>Download milestone events<\/li>\n\n\n\n<li>Application-wide notifications<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Key Principle<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>StateFlow represents what the application currently knows.<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>SharedFlow represents values broadcast through a shared stream.<\/strong><\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">15. SharedFlow vs Channel<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Kotlin also provides Channel for coroutine communication.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Channel Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>val channel = Channel&lt;String&gt;()<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">SharedFlow Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>val events = MutableSharedFlow&lt;String&gt;()<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Key Difference<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A Channel normally distributes each element to one receiver.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A SharedFlow broadcasts emissions to all active subscribers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Comparison<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Feature<\/th><th>SharedFlow<\/th><th>Channel<\/th><\/tr><tr><td>Multiple receivers<\/td><td>Yes<\/td><td>Yes<\/td><\/tr><tr><td>Broadcast each value to all<\/td><td>Yes, active subscribers<\/td><td>No, normally one receiver<\/td><\/tr><tr><td>Replay<\/td><td>Configurable<\/td><td>No replay cache<\/td><\/tr><tr><td>Buffering<\/td><td>Configurable<\/td><td>Configurable<\/td><\/tr><tr><td>Typical use<\/td><td>Broadcasting<\/td><td>Coroutine communication<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Neither mechanism automatically guarantees durable delivery across Android lifecycle changes or process death.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For critical events, consider persistent application state or a database-backed queue.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">16. Understanding shareIn()<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>shareIn()<\/code> operator converts a cold Flow into a hot SharedFlow.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This is useful when multiple collectors should share one upstream operation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class NewsRepository(\n    private val scope: CoroutineScope\n) {\n\n    private val newsFlow = flow {\n\n        while (true) {\n\n            emit(fetchLatestNews())\n\n            delay(5000)\n        }\n    }\n\n    val sharedNews = newsFlow.shareIn(\n        scope = scope,\n        started = SharingStarted.WhileSubscribed(5000),\n        replay = 1\n    )\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Assume fetchLatestNews() is an existing suspend function.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The upstream Flow is shared among subscribers.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Instead of creating a separate upstream operation for every collector, shareIn manages a shared producer.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Parameters<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>scope<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Defines the lifetime of sharing.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>started<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Controls when upstream collection starts and stops.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>replay<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Determines how many recent emissions are retained.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use an appropriately owned CoroutineScope.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid creating unmanaged long-lived scopes inside repositories.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">17. SharedFlow with ViewModel<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s create a ViewModel that broadcasts application messages.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class MessageViewModel : ViewModel() {\n\n    private val _messages =\n        MutableSharedFlow&lt;String&gt;(\n            extraBufferCapacity = 1\n        )\n\n    val messages: SharedFlow&lt;String&gt; =\n        _messages.asSharedFlow()\n\n    fun sendMessage(message: String) {\n\n        viewModelScope.launch {\n\n            _messages.emit(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\">The ViewModel exposes a read-only SharedFlow.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When sendMessage() is called, the message is emitted to active subscribers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Extra buffer capacity does not guarantee delivery when the UI is not collecting.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For messages that must remain visible after screen recreation, consider representing the message in UI state until it has been handled.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">18. Collecting SharedFlow in Jetpack Compose<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Jetpack Compose provides LaunchedEffect for running suspend operations associated with composition.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@Composable\nfun MessageScreen(\n    viewModel: MessageViewModel = viewModel()\n) {\n\n    val snackbarHostState = remember {\n        SnackbarHostState()\n    }\n\n    LaunchedEffect(viewModel) {\n\n        viewModel.messages.collect { message -&gt;\n\n            snackbarHostState.showSnackbar(message)\n        }\n    }\n\n    Scaffold(\n        snackbarHost = {\n            SnackbarHost(snackbarHostState)\n        }\n    ) { paddingValues -&gt;\n\n        Button(\n            onClick = {\n                viewModel.sendMessage(\n                    \"Message sent successfully\"\n                )\n            },\n            modifier = Modifier.padding(\n                paddingValues\n            )\n        ) {\n\n            Text(\"Send 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\">LaunchedEffect starts a coroutine when the effect enters composition.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The coroutine collects the SharedFlow.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When an event arrives, a Snackbar is displayed.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">LaunchedEffect is tied to composition, not automatically to the STARTED lifecycle state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For lifecycle-aware collection, use repeatOnLifecycle() when appropriate.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">19. Lifecycle-Aware SharedFlow Collection<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">For Android screens, lifecycle-aware collection can help avoid processing UI events while the screen is stopped.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@Composable\nfun LifecycleMessageScreen(\n    viewModel: MessageViewModel = viewModel()\n) {\n\n    val lifecycleOwner = LocalLifecycleOwner.current\n\n    val snackbarHostState = remember {\n        SnackbarHostState()\n    }\n\n    LaunchedEffect(\n        lifecycleOwner,\n        viewModel\n    ) {\n\n        lifecycleOwner.lifecycle.repeatOnLifecycle(\n            Lifecycle.State.STARTED\n        ) {\n\n            viewModel.messages.collect { message -&gt;\n\n                snackbarHostState.showSnackbar(message)\n            }\n        }\n    }\n\n    Scaffold(\n        snackbarHost = {\n            SnackbarHost(snackbarHostState)\n        }\n    ) { paddingValues -&gt;\n\n        Button(\n            onClick = {\n                viewModel.sendMessage(\n                    \"Operation completed\"\n                )\n            },\n            modifier = Modifier.padding(\n                paddingValues\n            )\n        ) {\n\n            Text(\"Perform Action\")\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 collector becomes active when the lifecycle reaches STARTED.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Collection stops when the lifecycle falls below STARTED.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Events emitted while collection is stopped may be missed when replay is zero.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This is expected SharedFlow behavior, not a lifecycle collection bug.<\/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: Download Status Events with SharedFlow<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Now let&#8217;s build a small Android application using:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Kotlin<\/li>\n\n\n\n<li>Jetpack Compose<\/li>\n\n\n\n<li>Material 3<\/li>\n\n\n\n<li>ViewModel<\/li>\n\n\n\n<li>StateFlow<\/li>\n\n\n\n<li>SharedFlow<\/li>\n\n\n\n<li>Kotlin Coroutines<\/li>\n\n\n\n<li>MVVM architecture<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The application will:<\/p>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li>Display a Start Download button.<\/li>\n\n\n\n<li>Simulate a download operation.<\/li>\n\n\n\n<li>Update download progress.<\/li>\n\n\n\n<li>Broadcast download milestone events.<\/li>\n\n\n\n<li>Display recent events.<\/li>\n\n\n\n<li>Show a Snackbar when the download completes.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">We&#8217;ll use StateFlow for current screen state and SharedFlow for event broadcasting.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This demonstrates how both APIs can work together.<\/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 Download Event Model<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>sealed interface DownloadEvent {\n\n    data object Started : DownloadEvent\n\n    data class Milestone(\n        val progress: Int\n    ) : DownloadEvent\n\n    data object Completed : DownloadEvent\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The event model represents three event types.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Download started<\/li>\n\n\n\n<li>Progress milestone reached<\/li>\n\n\n\n<li>Download completed<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Using a sealed interface makes event handling explicit.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">21. Create the Download UI State<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>data class DownloadUiState(\n    val isDownloading: Boolean = false,\n    val progress: Int = 0,\n    val isCompleted: Boolean = false\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This model represents the current download state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">StateFlow will expose it to Jetpack Compose.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">22. Create the Download ViewModel<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>class DownloadViewModel : ViewModel() {\n\n    private val _uiState = MutableStateFlow(\n        DownloadUiState()\n    )\n\n    val uiState: StateFlow&lt;DownloadUiState&gt; =\n        _uiState.asStateFlow()\n\n    private val _events =\n        MutableSharedFlow&lt;DownloadEvent&gt;(\n            extraBufferCapacity = 4\n        )\n\n    val events: SharedFlow&lt;DownloadEvent&gt; =\n        _events.asSharedFlow()\n\n    private var downloadJob: Job? = null\n\n    fun startDownload() {\n\n        if (downloadJob?.isActive == true) {\n            return\n        }\n\n        downloadJob = viewModelScope.launch {\n\n            _uiState.value = DownloadUiState(\n                isDownloading = true\n            )\n\n            _events.emit(DownloadEvent.Started)\n\n            for (progress in 1..100) {\n\n                delay(40)\n\n                _uiState.update { current -&gt;\n\n                    current.copy(\n                        progress = progress\n                    )\n                }\n\n                if (progress % 25 == 0 &amp;&amp; progress &lt; 100) {\n\n                    _events.emit(\n                        DownloadEvent.Milestone(progress)\n                    )\n                }\n            }\n\n            _uiState.update { current -&gt;\n\n                current.copy(\n                    isDownloading = false,\n                    isCompleted = true\n                )\n            }\n\n            _events.emit(DownloadEvent.Completed)\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 manages two streams.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>StateFlow<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Stores current download progress and completion state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>SharedFlow<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Broadcasts download milestones.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why Use Both?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Download progress is current state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Download milestones are events.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This separation makes the application easier to understand.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This tutorial simulates a download.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For a real file download, use an appropriate networking API and consider WorkManager or another suitable execution mechanism for work that must survive leaving the screen.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">23. Create the Jetpack Compose Download Screen<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>@Composable\nfun DownloadScreen(\n    viewModel: DownloadViewModel = viewModel()\n) {\n\n    val uiState by viewModel.uiState\n        .collectAsStateWithLifecycle()\n\n    val snackbarHostState = remember {\n        SnackbarHostState()\n    }\n\n    val lifecycleOwner = LocalLifecycleOwner.current\n\n    var recentEvents by remember {\n        mutableStateOf(emptyList&lt;String&gt;())\n    }\n\n    LaunchedEffect(\n        lifecycleOwner,\n        viewModel\n    ) {\n\n        lifecycleOwner.lifecycle.repeatOnLifecycle(\n            Lifecycle.State.STARTED\n        ) {\n\n            viewModel.events.collect { event -&gt;\n\n                val message = when (event) {\n\n                    DownloadEvent.Started -&gt;\n                        \"Download started\"\n\n                    is DownloadEvent.Milestone -&gt;\n                        \"Download ${event.progress}% completed\"\n\n                    DownloadEvent.Completed -&gt;\n                        \"Download completed successfully\"\n                }\n\n                recentEvents =\n                    (recentEvents + message).takeLast(5)\n\n                if (event == DownloadEvent.Completed) {\n\n                    snackbarHostState.showSnackbar(message)\n                }\n            }\n        }\n    }\n\n    Scaffold(\n        snackbarHost = {\n            SnackbarHost(snackbarHostState)\n        }\n    ) { paddingValues -&gt;\n\n        Column(\n            modifier = Modifier\n                .fillMaxSize()\n                .padding(paddingValues)\n                .padding(24.dp),\n            verticalArrangement = Arrangement.spacedBy(20.dp)\n        ) {\n\n            Text(\n                text = \"Download Manager\",\n                style = MaterialTheme.typography.headlineMedium\n            )\n\n            LinearProgressIndicator(\n                progress = {\n                    uiState.progress \/ 100f\n                },\n                modifier = Modifier.fillMaxWidth()\n            )\n\n            Text(\n                text = \"${uiState.progress}%\",\n                style = MaterialTheme.typography.titleLarge\n            )\n\n            Button(\n                onClick = {\n                    viewModel.startDownload()\n                },\n                enabled = !uiState.isDownloading\n            ) {\n\n                Text(\n                    if (uiState.isDownloading) {\n                        \"Downloading...\"\n                    } else {\n                        \"Start Download\"\n                    }\n                )\n            }\n\n            if (uiState.isCompleted) {\n\n                Text(\n                    text = \"Download completed\",\n                    color = MaterialTheme.colorScheme.primary\n                )\n            }\n\n            Text(\n                text = \"Recent Events\",\n                style = MaterialTheme.typography.titleMedium\n            )\n\n            recentEvents.forEach { event -&gt;\n\n                Text(\n                    text = \"\u2022 $event\"\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\">It also collects SharedFlow while the lifecycle is STARTED.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The current progress is displayed using a progress indicator.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Recent events appear in a small list.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A Snackbar is displayed when the download completes.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Production Note<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The recent-events list is local Compose state and is not intended as durable history.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If event history must survive screen recreation or process death, store it in ViewModel state or persistent storage.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Also, the completion status is already represented by StateFlow, so the UI can still show completion even if the SharedFlow completion event is missed.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">24. 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.MutableSharedFlow\nimport kotlinx.coroutines.flow.SharedFlow\nimport kotlinx.coroutines.flow.MutableStateFlow\nimport kotlinx.coroutines.flow.StateFlow\nimport kotlinx.coroutines.flow.asSharedFlow\nimport kotlinx.coroutines.flow.asStateFlow\nimport kotlinx.coroutines.flow.update<\/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.Lifecycle\nimport androidx.lifecycle.repeatOnLifecycle\nimport androidx.lifecycle.compose.LocalLifecycleOwner\nimport androidx.lifecycle.compose.collectAsStateWithLifecycle\nimport androidx.lifecycle.viewmodel.compose.viewModel<\/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.Column\nimport androidx.compose.foundation.layout.fillMaxSize\nimport androidx.compose.foundation.layout.fillMaxWidth\nimport androidx.compose.foundation.layout.padding\nimport androidx.compose.material3.Button\nimport androidx.compose.material3.LinearProgressIndicator\nimport androidx.compose.material3.MaterialTheme\nimport androidx.compose.material3.Scaffold\nimport androidx.compose.material3.SnackbarHost\nimport androidx.compose.material3.SnackbarHostState\nimport androidx.compose.material3.Text\nimport androidx.compose.runtime.Composable\nimport androidx.compose.runtime.LaunchedEffect\nimport androidx.compose.runtime.getValue\nimport androidx.compose.runtime.mutableStateOf\nimport androidx.compose.runtime.remember\nimport androidx.compose.runtime.setValue\nimport androidx.compose.ui.Modifier\nimport androidx.compose.ui.unit.dp<\/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. Expected UI \u2014 Initial State<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>+--------------------------------+\n|                                |\n|       Download Manager         |\n|                                |\n| &#91;--------------------------]   |\n|                                |\n|              0%                |\n|                                |\n|       &#91; Start Download ]       |\n|                                |\n| Recent Events                  |\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\">26. Expected UI \u2014 Downloading<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>+--------------------------------+\n|                                |\n|       Download Manager         |\n|                                |\n| &#91;#############-------------]   |\n|                                |\n|             50%                |\n|                                |\n|        Downloading...          |\n|                                |\n| Recent Events                  |\n|                                |\n| \u2022 Download started             |\n| \u2022 Download 25% completed       |\n| \u2022 Download 50% completed       |\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\">27. Expected UI \u2014 Completed<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>+--------------------------------+\n|                                |\n|       Download Manager         |\n|                                |\n| &#91;##########################]   |\n|                                |\n|             100%               |\n|                                |\n|       &#91; Start Download ]       |\n|                                |\n| Download completed             |\n|                                |\n| Recent Events                  |\n|                                |\n| \u2022 Download 25% completed       |\n| \u2022 Download 50% completed       |\n| \u2022 Download 75% completed       |\n| \u2022 Download completed           |\n|                                |\n+--------------------------------+<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">A Snackbar may also appear:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Download completed successfully<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">28. How the Complete Application Works<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Step 1: User Starts Download<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The user taps Start Download.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 2: ViewModel Starts a Coroutine<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel launches a coroutine using viewModelScope.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 3: StateFlow Updates Progress<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The progress value changes from 0 to 100.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 4: SharedFlow Broadcasts Events<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel emits Started, Milestone, and Completed events.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 5: Compose Observes StateFlow<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The progress indicator updates automatically.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 6: Compose Collects SharedFlow<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The active collector receives milestone messages.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 7: Download Completes<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">StateFlow records completion.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">SharedFlow broadcasts the completion event.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 8: UI Displays Result<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The UI shows completion state and, when the event is received, displays a Snackbar.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This demonstrates the different responsibilities of StateFlow and SharedFlow.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">29. Common SharedFlow Mistakes<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 1: Assuming Every Event Is Delivered<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">SharedFlow does not guarantee delivery to collectors that are not active.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 2: Using Replay for Every UI Event<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Replay can cause old events to be handled again.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 3: Confusing Buffering with Persistence<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">SharedFlow buffering is in-memory and is not durable storage.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 4: Ignoring Lifecycle Changes<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Collectors may stop when screens become inactive.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Design event delivery accordingly.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 5: Assuming tryEmit() Guarantees Processing<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">tryEmit() reports whether the value was accepted, not whether a subscriber handled it.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 6: Using SharedFlow for All UI State<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use StateFlow for current screen state.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 7: Forgetting to Cancel Collectors<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">SharedFlow collection does not normally complete.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use structured concurrency and lifecycle-aware scopes.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 8: Creating Unmanaged Application-Wide Scopes<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use clearly owned CoroutineScopes for shared producers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 9: Ignoring Buffer Overflow Behavior<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Choose SUSPEND, DROP_OLDEST, or DROP_LATEST based on the requirements.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 10: Treating SharedFlow as a Persistent Queue<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For important operations, use persistent state or an appropriate durable queue.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">30. Kotlin SharedFlow 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>Use SharedFlow for appropriate broadcast streams.<\/li>\n\n\n\n<li>Use StateFlow for current UI state.<\/li>\n\n\n\n<li>Keep MutableSharedFlow private.<\/li>\n\n\n\n<li>Expose read-only SharedFlow.<\/li>\n\n\n\n<li>Choose replay values intentionally.<\/li>\n\n\n\n<li>Understand buffering and overflow strategies.<\/li>\n\n\n\n<li>Preserve coroutine cancellation.<\/li>\n\n\n\n<li>Use lifecycle-aware collection for Android UI.<\/li>\n\n\n\n<li>Avoid depending on events emitted without subscribers.<\/li>\n\n\n\n<li>Use viewModelScope for ViewModel-owned work.<\/li>\n\n\n\n<li>Use shareIn() when multiple collectors should share upstream work.<\/li>\n\n\n\n<li>Use appropriate CoroutineScope ownership.<\/li>\n\n\n\n<li>Test event delivery and lifecycle behavior.<\/li>\n\n\n\n<li>Avoid using SharedFlow as durable storage.<\/li>\n\n\n\n<li>Prefer explicit state for important user-visible outcomes.<\/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. Kotlin SharedFlow Quick Reference<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Concept<\/th><th>Purpose<\/th><\/tr><tr><td>SharedFlow<\/td><td>Hot broadcast stream<\/td><\/tr><tr><td>MutableSharedFlow<\/td><td>Mutable broadcast stream<\/td><\/tr><tr><td>asSharedFlow()<\/td><td>Expose read-only interface<\/td><\/tr><tr><td>emit()<\/td><td>Suspending emission<\/td><\/tr><tr><td>tryEmit()<\/td><td>Non-suspending emission attempt<\/td><\/tr><tr><td>replay<\/td><td>Retain recent values<\/td><\/tr><tr><td>replayCache<\/td><td>Inspect replayed values<\/td><\/tr><tr><td>extraBufferCapacity<\/td><td>Additional buffering<\/td><\/tr><tr><td>BufferOverflow.SUSPEND<\/td><td>Suspend when needed<\/td><\/tr><tr><td>BufferOverflow.DROP_OLDEST<\/td><td>Drop oldest buffered values<\/td><\/tr><tr><td>BufferOverflow.DROP_LATEST<\/td><td>Drop new values when full<\/td><\/tr><tr><td>subscriptionCount<\/td><td>Observe subscriber count<\/td><\/tr><tr><td>shareIn()<\/td><td>Convert Flow into shared hot stream<\/td><\/tr><tr><td>repeatOnLifecycle()<\/td><td>Lifecycle-aware collection<\/td><\/tr><tr><td>viewModelScope<\/td><td>ViewModel-owned coroutine scope<\/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\">32. Practical Exercises<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Try these exercises to improve your understanding.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 1: Basic SharedFlow<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Create a MutableSharedFlow that emits three messages.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 2: Multiple Collectors<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Create two collectors that receive the same events.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 3: Replay<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Configure replay = 2 and verify that a new collector receives the last two values.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 4: Buffering<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Experiment with extraBufferCapacity.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 5: Overflow Strategies<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Compare SUSPEND, DROP_OLDEST, and DROP_LATEST.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 6: emit vs tryEmit<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Test both emission methods under different buffer configurations.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 7: subscriptionCount<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Observe the number of active subscribers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 8: ViewModel Integration<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Create a ViewModel that exposes a read-only SharedFlow.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 9: Jetpack Compose<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Collect SharedFlow events and display a Snackbar.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 10: Download Manager<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Build the complete download status mini-project 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\">33. Frequently Asked Questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">What is SharedFlow in Kotlin?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">SharedFlow is a hot Flow that broadcasts values to multiple subscribers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is MutableSharedFlow?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">MutableSharedFlow is the mutable implementation used to emit values into a SharedFlow.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is the difference between SharedFlow and StateFlow?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">StateFlow represents current observable state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">SharedFlow broadcasts values and supports configurable replay and buffering.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does SharedFlow require an initial value?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No. SharedFlow does not require an initial value.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is replay in SharedFlow?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Replay determines how many recent values are delivered to new subscribers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is extraBufferCapacity?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">It provides additional buffering capacity for active subscribers beyond the replay cache.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is the difference between emit and tryEmit?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">emit() is suspending and can wait when necessary.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">tryEmit() is non-suspending and returns whether the value was accepted.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does SharedFlow guarantee event delivery?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No. Delivery depends on active subscribers, replay, buffering, cancellation, and other stream behavior.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can SharedFlow be used with Jetpack Compose?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. SharedFlow can be collected in Compose using LaunchedEffect and lifecycle-aware collection APIs.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is shareIn()?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">shareIn converts a cold Flow into a hot SharedFlow within a CoroutineScope.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Should SharedFlow be used for navigation events?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">It can be used for event broadcasting, but navigation outcomes that must survive lifecycle changes are often better modeled as durable UI state.<\/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 SharedFlow fundamentals<\/li>\n\n\n\n<li>Hot streams<\/li>\n\n\n\n<li>MutableSharedFlow vs SharedFlow<\/li>\n\n\n\n<li>Multiple collectors<\/li>\n\n\n\n<li>Replay cache<\/li>\n\n\n\n<li>Buffering<\/li>\n\n\n\n<li>Overflow strategies<\/li>\n\n\n\n<li>emit vs tryEmit<\/li>\n\n\n\n<li>subscriptionCount<\/li>\n\n\n\n<li>SharedFlow vs StateFlow<\/li>\n\n\n\n<li>SharedFlow vs Channel<\/li>\n\n\n\n<li>shareIn<\/li>\n\n\n\n<li>ViewModel integration<\/li>\n\n\n\n<li>Jetpack Compose integration<\/li>\n\n\n\n<li>Lifecycle-aware collection<\/li>\n\n\n\n<li>Download status 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\">SharedFlow is a useful tool for broadcasting asynchronous values to multiple collectors.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, successful Android development requires choosing the correct mechanism for each responsibility.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use StateFlow for current UI 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<p class=\"wp-block-paragraph\">Use persistent state or durable storage when information must survive lifecycle changes or process death.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By understanding these differences, developers can build more reliable Android applications using Kotlin Coroutines, ViewModel, and Jetpack Compose.<\/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 Exception Handling &amp; Retry: catch, retry, retryWhen &amp; Android Best Practices<\/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>Flow exception propagation<\/li>\n\n\n\n<li>catch operator<\/li>\n\n\n\n<li>retry operator<\/li>\n\n\n\n<li>retryWhen operator<\/li>\n\n\n\n<li>CancellationException<\/li>\n\n\n\n<li>Network error handling<\/li>\n\n\n\n<li>Retry with exponential backoff<\/li>\n\n\n\n<li>Flow completion handling<\/li>\n\n\n\n<li>ViewModel error state<\/li>\n\n\n\n<li>Jetpack Compose error and retry UI<\/li>\n\n\n\n<li>Practical Android examples<\/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 SharedFlow with practical Android examples covering hot streams, event broadcasting, replay, buffering, emit vs tryEmit, ViewModel integration, and Jetpack Compose.<\/p>\n","protected":false},"author":1,"featured_media":164,"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-163","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\/163","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=163"}],"version-history":[{"count":1,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/163\/revisions"}],"predecessor-version":[{"id":165,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/163\/revisions\/165"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/media\/164"}],"wp:attachment":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/media?parent=163"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/categories?post=163"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/tags?post=163"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}