Skip to content

Instantly share code, notes, and snippets.

@makorowy
Created November 22, 2020 14:43
Show Gist options
  • Save makorowy/c1cc719e97222218d97de28da3d0a5af to your computer and use it in GitHub Desktop.
Save makorowy/c1cc719e97222218d97de28da3d0a5af to your computer and use it in GitHub Desktop.
[BLOG] Example of ViewModel implementation with ViewState and Interactions
class SettingsViewModel(
settingsRepository: SettingsRepository
) : ViewModel() {
private var currentViewState = ViewState(
firstName = "",
lastName = "",
notificationsChecked = false,
notificationsEnabled = false
)
private val _viewState = MutableLiveData<ViewState>()
val viewState: LiveData<ViewState> = _viewState
init {
val settings = settingsRepository.settings
submitViewState(
ViewState(
firstName = settings.firstName,
lastName = settings.lastName,
notificationsChecked = settings.notificationsChecked,
notificationsEnabled = settings.notificationsChecked
)
)
}
private fun submitViewState(viewState: ViewState) {
currentViewState = viewState
_viewState.postValue(currentViewState)
}
fun onInteraction(interaction: Interaction) {
when (interaction) {
is NotificationSwitchChanged -> notificationsSwitchChanged(interaction.enabled)
is FirstNameChange -> firstNameChanged(interaction.firstName)
is LastNameChange -> lastNameChanged(interaction.lastName)
is NotificationSettingButtonClick -> notificationsSettingsButtonClicked()
is HelpButtonButtonClick -> helpButtonClicked()
is LogOutButtonClick -> logOutButtonClicked()
is AdvancedSettingsButtonClick -> advancedSettingsButtonClicked()
}
}
private fun notificationsSwitchChanged(checked: Boolean) {
submitViewState(
currentViewState.copy(
notificationsChecked = checked,
notificationsEnabled = checked
)
)
/* logic */
}
private fun firstNameChanged(name: String) {
/* logic */
}
private fun lastNameChanged(name: String) {
/* logic */
}
private fun notificationsSettingsButtonClicked() {
/* logic */
}
private fun helpButtonClicked() {
/* logic */
}
private fun logOutButtonClicked() {
/* logic */
}
private fun advancedSettingsButtonClicked() {
/* logic */
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment