您可以在ViewModel
中实现一些基本的缓存.以下是ViewModel
在配置更改期间将缓存数据返回给订阅者的假设示例.
class MainViewModel : ViewModel() {
sealed interface MainViewState {
data object Content : MainViewState
data object Loading : MainViewState
data class Error(val error: Throwable) : MainViewState
}
private val _viewState: MutableStateFlow<MainViewState> =
MutableStateFlow(MainViewState.Loading)
val viewState = _viewState.asStateFlow()
init {
loadData()
}
private fun loadData() = viewModelScope.launch {
// We have cached data, do nothing, StateFlow will re-emit latest state to new subscribers
if (_viewState.value == MainViewState.Content) {
return@launch
}
_viewState.update {
MainViewState.Loading
}
// Load some data and return MainViewState.Content or MainViewState.Error
}
}