如何处理使用带有状态的密封类的 ViewModel 内部的程序错误?

问题描述 投票:0回答:0

尽力去理解

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
?或者有什么更好的方法吗?

database kotlin mvvm android-room flow
© www.soinside.com 2019 - 2024. All rights reserved.