According to my little knowledge:
In MVVM (Model-View-ViewModel) architectural pattern, the view should notify the view-model for user interactions such as button clicks. The view-model responds by updating its observable data streams (LiveData) that the view would be observing. Hence the view would update the UI and the user sees the result.
But lets consider some trivial case when the user actions have only UI consequence with no data related or manipulated. For example: a Button that when clicked, toggles the visibility of another UI widget.
My question is how to handle this simple case while still applying MVVM correctly? Should I directly update the UI without notifying the ViewModel?
First off all for all UI related things, you should absolutely notify ViewModel. You can define the event as follow in the ViewModel. BTW _itemClickedEvent defined for encapsulation.
private val _itemClickedEvent = MutableLiveData<Boolean>()
var itemClickedEvent: LiveData<Boolean> = _itemClickedEvent
fun itemClickedEvent(state: Boolean) {
_itemClickedEvent.value = state
}
After that you can call itemClickedEvent via viewModel object for your scenario.
button.setOnClickListener {
viewModel.itemClickedEvent(true)
}
By observing LiveData you can do your visibility or any other UI related things as below
viewModel.itemClickedEvent.observe(this, Observer {isItemClicked->
if(isItemClicked){
// Do your changes
}
})