Skip to content

Instantly share code, notes, and snippets.

@makorowy
Created November 22, 2020 14:44
Show Gist options
  • Save makorowy/ca69df15e280178786f75f47e3c566fc to your computer and use it in GitHub Desktop.
Save makorowy/ca69df15e280178786f75f47e3c566fc to your computer and use it in GitHub Desktop.
[BLOG] Example of Fragment handling ViewModel's ViewState and Interactions
class SettingsFragment : Fragment() {
private val viewModel: SettingsViewModel2 by viewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setInteractions()
observeViewState()
}
private fun setInteractions() {
notificationsSwitch.setOnCheckedChangeListener { checked ->
viewModel.onInteraction(NotificationSwitchChanged(checked))
}
notificationsButton.setOnClickListener {
viewModel.onInteraction(NotificationSettingButtonClick)
}
/* other interactions */
}
private fun observeViewState() {
viewModel.viewState.observe(viewLifecycleOwner, Observer { viewState ->
render(viewState ?: return@Observer)
})
}
private fun render(viewState: ViewState) {
renderName(viewState)
renderNotifications(viewState)
}
private fun renderName(viewState: ViewState) {
firstNameText.text = viewState.firstName
lastNameText.text = viewState.lastName
}
private fun renderNotifications(viewState: ViewState) {
notificationzSwitch.isChecked = viewState.notificationsChecked
notificationsButton.isEnabled = viewState.notificationsEnabled
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment