SharedFlow
A hot flow that can emit multiple values and has no initial value. Supports replay and buffer.
Basic Usage
Section titled “Basic Usage”class MyViewModel : ViewModel() { private val _events = MutableSharedFlow<String>() val events: SharedFlow<String> = _events.asSharedFlow()
fun sendEvent(event: String) { viewModelScope.launch { _events.emit(event) } }}SharedFlow with Replay
Section titled “SharedFlow with Replay”// Replay last 3 values to new collectorsprivate val _events = MutableSharedFlow<String>(replay = 3)Collect SharedFlow in Composable
Section titled “Collect SharedFlow in Composable”@Composablefun MyScreen(viewModel: MyViewModel = viewModel()) { LaunchedEffect(Unit) { viewModel.events.collect { event -> // Handle one-time events (e.g., show snackbar, navigate) println("Event received: $event") } }}When to Use SharedFlow
Section titled “When to Use SharedFlow”- One-time events (navigation, snackbar, toast)
- Events that should not be replayed on configuration change
- Broadcasting to multiple collectors