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

To use the by keyword in compose, import:

import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
var count by remember { mutableStateOf(0) }
key(count){
// recompose when the var count change
}

Kind of like LaunchedEffect but allows use in non-composable functions

snapshotFlow { searchQuery }
.filter { it.length > 2 } // Only emit if query is longer than 2 characters
.debounce(500) // Wait 500ms after last change
.collect { query ->
println("Search query: $query")
// Example: Trigger a network search
}