SharedFlow vs. StateFlow: Best Practices and Real-world examples
<p>Dive into the world of Kotlin flows with this in-depth comparison of SharedFlow and StateFlow. Here’s an overview of both types of flows and their use cases:</p>
<p><code>SharedFlow</code> and <code>StateFlow</code> are both parts of Kotlin's <code>kotlinx.coroutines</code> library, specifically designed to handle asynchronous data streams. Both are built on top of <code>Flow</code> and are meant for different purposes.</p>
<ol>
<li>SharedFlow:</li>
</ol>
<ul>
<li>A <code>SharedFlow</code> is a hot flow that can have multiple collectors. It can emit values independently of the collectors, and multiple collectors can collect the same values from the flow.</li>
<li>It’s useful when you need to broadcast a value to multiple collectors or when you want to have multiple subscribers to the same stream of data.</li>
<li>It does not have an initial value, and you can configure its replay cache to store a certain number of previously emitted values for new collectors.</li>
</ul>
<p><img alt="" src="https://miro.medium.com/v2/resize:fit:770/1*tu6KalOk971mR6yC5LmFQQ.png" style="height:378px; width:700px" /></p>
<p>SharedFlow can broadcast values to multiple collectors simultaneously</p>
<p>Example usage:</p>
<pre>
val sharedFlow = MutableSharedFlow<Int>()
// Collect values from sharedFlow
launch {
sharedFlow.collect { value ->
println("Collector 1 received: $value")
}
}
// Collect values from sharedFlow
launch {
sharedFlow.collect { value ->
println("Collector 2 received: $value")
}
}
// Emit values to sharedFlow
launch {
repeat(3) { i ->
sharedFlow.emit(i)
}
}</pre>
<ol>
<li>StateFlow:</li>
</ol>
<ul>
<li>A <code>StateFlow</code> is a hot flow that represents a state, holding a single value at a time. It is also a conflated flow, meaning that when a new value is emitted, the most recent value is retained and immediately emitted to new collectors.</li>
<li>It is useful when you need to maintain a single source of truth for a state and automatically update all the collectors with the latest state.</li>
<li>It always has an initial value and only stores the latest emitted value.</li>
</ul>
<p> <a href="https://medium.com/@mortitech/sharedflow-vs-stateflow-a-comprehensive-guide-to-kotlin-flows-503576b4de31">Visit Now</a></p>