🐦 Kotlin Intermediate

What is StateFlow in Kotlin?

Answer

StateFlow is a hot flow that holds the current state value and replays it to new collectors. It is a modern, coroutine-friendly replacement for LiveData in Android. Unlike a regular cold Flow, StateFlow is always active and always has a value. New collectors immediately receive the current value on subscription. Update the state by assigning to a MutableStateFlow's value property. In ViewModels, expose it as the immutable interface: private val _uiState = MutableStateFlow(initialState); val uiState: StateFlow<State> = _uiState.asStateFlow().