Android MVVM:视图是否应该为每个用户交互通知视图模型,即使是微不足道的交互(只有 UI consequence/no 数据)

Android MVVM: Should the view notify the view-model for every user interaction even trivial ones (only have UI consequence/no data)

据我所知:

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.

但是让我们考虑一些微不足道的情况,当用户操作只产生 UI 结果而没有相关或操纵的数据时。例如:一个 Button,在单击时会切换另一个 UI 小部件的可见性。

我的问题是如何在正确应用 MVVM 的同时处理这个简单的案例? 我应该直接更新 UI 而不通知 ViewModel 吗?

首先,对于所有 UI 相关的事情,您绝对应该通知 ViewModel。您可以在 ViewModel 中如下定义事件。顺便说一句,为封装定义了_itemClickedEvent。

private val _itemClickedEvent = MutableLiveData<Boolean>()

var itemClickedEvent: LiveData<Boolean> = _itemClickedEvent

fun itemClickedEvent(state: Boolean) {
    _itemClickedEvent.value = state
}

之后您可以通过 viewModel 对象为您的场景调用 itemClickedEvent。

button.setOnClickListener {
            viewModel.itemClickedEvent(true)
        }

通过观察 LiveData,您可以进行可见性或任何其他 UI 相关的事情,如下所示

viewModel.itemClickedEvent.observe(this, Observer {isItemClicked->
        if(isItemClicked){
            // Do your changes
        }
    })