Skip to content

Instantly share code, notes, and snippets.

@jmadaminov
Last active November 1, 2022 14:28
Show Gist options
  • Save jmadaminov/5bb7d207ae263b9ae2ef7b7e3313d3e2 to your computer and use it in GitHub Desktop.
Save jmadaminov/5bb7d207ae263b9ae2ef7b7e3313d3e2 to your computer and use it in GitHub Desktop.
UI-Event test ViewModel
const val SECONDS = 5
class MainViewModel : ViewModel() {
private var timerJob: Job? = null
private val _uiState = MutableStateFlow(MainUiState())
val uiState = _uiState.asStateFlow()
fun makeApiCall() {
timerJob?.cancel()
timerJob = viewModelScope.launch {
repeat(SECONDS) { repeatIndex ->
_uiState.update { it.copy(time = SECONDS - 1 * repeatIndex) }
delay(1000)
}
_uiState.update { it.copy(time = 0, error = "Something went wrong!") }
}
}
fun errorToastShown() {
_uiState.update { it.copy(error = null) }
}
}
data class MainUiState(val time: Int = SECONDS, val error: String? = null)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment