Skip to content

Instantly share code, notes, and snippets.

@makorowy
Last active October 18, 2020 09:46
Show Gist options
  • Select an option

  • Save makorowy/bbc770581058b04b367c59f1dd7c5687 to your computer and use it in GitHub Desktop.

Select an option

Save makorowy/bbc770581058b04b367c59f1dd7c5687 to your computer and use it in GitHub Desktop.
Example of not handling interactions via ViewModel, part 4
data class ModelData(
val progressVisible: Boolean,
)
class ViewModel(
private val repository: Repository,
private val navigator: Navigator
) : ViewModel() {
private val _liveData = MutableLiveData<ModelData>()
val liveData: LiveData<ModelData> = _liveData
private val observer: (RepositoryData) -> Unit = { repositoryData ->
//map repository data to view model data
//to siplify let's just change the progress visibility state
_liveData.postValue(ModelData(progressVisible = false))
}
init {
repository.observeChanges(observer)
}
fun onInteraction(interaction: Interaction) {
when (interaction) {
is Interaction.BackButtonClick -> onBackButtonClicked()
is Interaction.SkipButtonClick -> onSkipButtonClicked()
is Interaction.SaveButtonClick -> onSaveButtonClicked()
is Interaction.NameChange -> onNameChanged(interaction.name)
}
}
private fun onBackButtonClicked() {
navigator.navigateBack()
}
private fun onSkipButtonClicked() {
navigator.navigateForward()
}
private fun onSaveButtonClicked() {
_liveData.postValue(ModelData(progressVisible = true)
repository.doSomethingAsync()
//additional logic
//update view state or let changes from repository to do it
}
private fun onNameChanged() {
repository.saveName(name)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment