尽力去理解
StateFlow
和States
。根据android文档,我们有这段代码:
class LatestNewsViewModel(
private val newsRepository: NewsRepository
) : ViewModel() {
// Backing property to avoid state updates from other classes
private val _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
sealed class LatestNewsUiState {
data class Success(val news: List<ArticleHeadline>): LatestNewsUiState()
data class Error(val exception: Throwable): LatestNewsUiState()
}
现在,如果我想处理错误,根据
LatestNewUiState
密封类 - 我是否必须创建另一个支持属性,如 _uiStateError = ...
有一个地方,放入错误,然后创建另一个 val ,
val uiStateError: MutableStateFlow<LatestNewsUiState> = _uiStateError
然后,用viewModelScope.launch
包裹try/catch
,每当发生错误时,只需将Throwable
推到_uiStateError
?或者有什么更好的方法吗?