Skip to content

StateFlow

A hot flow that holds a single value and emits updates to collectors. Always has an initial value.

class MyViewModel : ViewModel() {
private val _uiState = MutableStateFlow("Initial")
val uiState: StateFlow<String> = _uiState.asStateFlow()
fun updateState(newValue: String) {
_uiState.value = newValue
}
}
@Composable
fun MyScreen(viewModel: MyViewModel = viewModel()) {
val uiState by viewModel.uiState.collectAsState()
Text(text = uiState)
}
StateFlowLiveData
Requires initial valueCan be null initially
Kotlin coroutines basedLifecycle-aware by default
collectAsState() in ComposeobserveAsState() in Compose
StateFlowSharedFlow
Always has current valueNo initial value required
.value to read currentNo .value property
Conflates (skips intermediate)Configurable buffer/replay
Best for UI stateBest for events/actions