// Backing property to avoid state updates from other classes privateval _uiState = MutableStateFlow(LatestNewsUiState.Success(emptyList())) // The UI collects from this StateFlow to get its state updates val uiState: StateFlow<LatestNewsUiState> = _uiState
init { viewModelScope.launch { newsRepository.favoriteLatestNews // Update View with the latest favorite news // Writes to the value property of MutableStateFlow, // adding a new element to the flow and updating all // of its collectors .collect { favoriteNews -> _uiState.value = LatestNewsUiState.Success(favoriteNews) } } } }
// Represents different states for the LatestNews screen sealedclassLatestNewsUiState { dataclassSuccess(val news: List<ArticleHeadline>): LatestNewsUiState() dataclassError(val exception: Throwable): LatestNewsUiState() }