Created
November 22, 2020 14:44
-
-
Save makorowy/ca69df15e280178786f75f47e3c566fc to your computer and use it in GitHub Desktop.
[BLOG] Example of Fragment handling ViewModel's ViewState and Interactions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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