SharedFlow vs. StateFlow: Best Practices and Real-world examples

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:

SharedFlow and StateFlow are both parts of Kotlin's kotlinx.coroutines library, specifically designed to handle asynchronous data streams. Both are built on top of Flow and are meant for different purposes.

  1. SharedFlow:
  • SharedFlow 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.
  • 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.
  • 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.

SharedFlow can broadcast values to multiple collectors simultaneously

Example usage:

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)
    }
}
  1. StateFlow:
  • StateFlow 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.
  • 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.
  • It always has an initial value and only stores the latest emitted value.

 Visit Now