StateFlow and SharedFlow help apps handle data that changes over time. They let your app react to updates smoothly and keep the user interface fresh.
0
0
StateFlow and SharedFlow in Android Kotlin
Introduction
When you want to show live data like user input or sensor updates.
When multiple parts of your app need to listen to the same data changes.
When you want to keep the latest state and share it safely across your app.
When you want to send one-time events like navigation commands or messages.
When you want to avoid manual callbacks and use a simple flow of data.
Syntax
Android Kotlin
val stateFlow = MutableStateFlow(initialValue)
val sharedFlow = MutableSharedFlow<T>(replay = 0)StateFlow always holds the latest value and emits it to new collectors.
SharedFlow can emit events without holding a value, useful for one-time actions.
Examples
This creates a StateFlow holding an integer and updates its value.
Android Kotlin
val countState = MutableStateFlow(0) countState.value = 1
This creates a SharedFlow for strings and emits a message event.
Android Kotlin
val eventFlow = MutableSharedFlow<String>()
launch { eventFlow.emit("Hello") }This SharedFlow replays the last 2 emitted values to new collectors.
Android Kotlin
val replayFlow = MutableSharedFlow<Int>(replay = 2)Sample App
This program shows how StateFlow keeps the latest number and SharedFlow sends events. Both are collected and printed.
Android Kotlin
import kotlinx.coroutines.* import kotlinx.coroutines.flow.* fun main() = runBlocking { val stateFlow = MutableStateFlow(0) val sharedFlow = MutableSharedFlow<String>() // Collect StateFlow val job1 = launch { stateFlow.collect { value -> println("StateFlow value: $value") } } // Collect SharedFlow val job2 = launch { sharedFlow.collect { event -> println("SharedFlow event: $event") } } // Update StateFlow stateFlow.value = 1 delay(100) stateFlow.value = 2 // Emit SharedFlow events sharedFlow.emit("First event") sharedFlow.emit("Second event") delay(100) job1.cancel() job2.cancel() }
OutputSuccess
Important Notes
StateFlow always has a current value; SharedFlow does not have to hold a value.
Use StateFlow for state that changes over time and SharedFlow for events or messages.
Both flows are hot flows that share emissions with multiple collectors.
Summary
StateFlow holds and emits the latest state value.
SharedFlow emits events to multiple collectors without holding state.
Use them to build reactive and responsive Android apps easily.