Skip to content

Instantly share code, notes, and snippets.

@Raiden18
Last active July 21, 2022 19:06
Show Gist options
  • Save Raiden18/966a60e519fee8bbe43c4f505c872305 to your computer and use it in GitHub Desktop.
Save Raiden18/966a60e519fee8bbe43c4f505c872305 to your computer and use it in GitHub Desktop.
SomeViewModel example
sealed class ContentState {
object Hidden : ContentState()
data class Shown(val data: String) : ContentState()
}
class SomeViewModel(
private val someInteractor: SomeInteractor,
private val dispatchersProvider: DispatchersProvider
) : ViewModel() {
private val isLoaderViewVisibleStateFlow = MutableStateFlow(false)
private val isErrorViewVisibleStateFlow = MutableStateFlow(false)
private val contentStateStateFlow = MutableStateFlow<ContentState>(ContentState.Hidden)
init {
loadInitialData()
}
fun onRetryButtonClicked() {
loadInitialData()
}
private fun loadInitialData() = viewModelScope.launch(dispatchersProvider.io) {
showLoaderState()
// Another error handling strategy could be used. It's not important for the article.
try {
val data = someInteractor.doSomething()
showContentState(data)
} catch (throwable: Throwable) {
showErrorState()
}
}
private fun showContentState(data: String) {
isErrorViewVisibleStateFlow.value = false
isLoaderViewVisibleStateFlow.value = false
contentStateStateFlow.value = ContentState.Shown(data)
}
private fun showErrorState() {
isLoaderViewVisibleStateFlow.value = false
isErrorViewVisibleStateFlow.value = true
contentStateStateFlow.value = ContentState.Hidden
}
private fun showLoaderState() {
isErrorViewVisibleStateFlow.value = false
isLoaderViewVisibleStateFlow.value = true
contentStateStateFlow.value = ContentState.Hidden
}
fun getLoaderState(): StateFlow<Boolean> = isLoaderViewVisibleStateFlow
fun getErrorState(): StateFlow<Boolean> = isErrorViewVisibleStateFlow
fun getContentState(): StateFlow<ContentState> = contentStateStateFlow
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment