What is SharedFlow and how does it differ from StateFlow?
sobes.tech AI
Answer from AI
SharedFlow and StateFlow are both types of flows from the kotlinx.coroutines library, designed for reactive programming and managing asynchronous data streams, but they have different purposes and behaviors.
StateFlow is a flow that always contains the current state (value). It is similar to an Observable with the latest value, which can be accessed at any time. StateFlow always holds a single current value and emits it immediately upon subscription. This is convenient for representing UI state or other data that should have a current value.
SharedFlow is a more general flow that can have multiple subscribers and does not hold state by default. It can be configured with a buffer and replay policies. SharedFlow is used for broadcasting events that do not necessarily need to have a current value, such as navigation events, notifications, or one-time signals.
Key differences:
- StateFlow always contains the current state, SharedFlow does not (if replay=0).
- StateFlow emits the current value immediately upon subscription, SharedFlow does so only if configured with replay.
- SharedFlow is more flexible and suitable for events, StateFlow for state.
Example of using StateFlow:
val stateFlow = MutableStateFlow(0)
// Updating state
stateFlow.value = 1
// Subscription
stateFlow.collect { value ->
println("Current value: $value")
}
Example of SharedFlow with replay:
val sharedFlow = MutableSharedFlow<Int>(replay = 1)
// Emitting an event
sharedFlow.emit(42)
// New subscriber will receive the last event thanks to replay
sharedFlow.collect { event ->
println("Received event: $event")
}