🎉 Smithery is now a part of Arcade.dev! Read more in our announcement here
Best practices for implementing Android ViewModels, specifically focused on StateFlow for UI state and SharedFlow for one-off events.
Use ViewModel to hold state and business logic. It must outlive configuration changes.
ViewModel
Loading
Success(data)
Error
StateFlow<UiState>
StateFlow
MutableStateFlow
private val _uiState = MutableStateFlow<UiState>(UiState.Loading) val uiState: StateFlow<UiState> = _uiState.asStateFlow()
.update { oldState -> ... }
SharedFlow<UiEvent>
replay = 0
private val _uiEvent = MutableSharedFlow<UiEvent>(replay = 0) val uiEvent: SharedFlow<UiEvent> = _uiEvent.asSharedFlow()
.emit(event)
.tryEmit(event)
collectAsStateWithLifecycle()
val state by viewModel.uiState.collectAsStateWithLifecycle()
SharedFlow
LaunchedEffect
LocalLifecycleOwner
repeatOnLifecycle(Lifecycle.State.STARTED)
viewModelScope