StateFlow is a state-holder observable flow that is designed to hold a single updatable data value and emit updates to its collectors. It is particularly useful in Jetpack Compose for managing UI state in a reactive way. When combined with ViewModel, it allows for a clean separation of UI and state logic, making it easier to manage complex UI states.
import androidx.compose.runtime.collectAsState
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
class MyViewModel : ViewModel() {
private val _uiState = MutableStateFlow("Initial State")
val uiState: StateFlow = _uiState
fun updateState(newState: String) {
_uiState.value = newState
}
}
// In your Composable function
@Composable
fun MyScreen(viewModel: MyViewModel) {
val uiState = viewModel.uiState.collectAsState()
Text(text = uiState.value)
Button(onClick = { viewModel.updateState("Updated State") }) {
Text("Update State")
}
}