谷歌关于mvvm的官方示例地址:
https://github.com/googlesamples/android-architecture/tree/dev-todo-mvvm-databinding/
MVP( Model-View-Presenter)和MVVM (Model-View-ViewModel) 的区别引用官方的话就是
The ViewModel in MVVM is very similar to the Presenter in MVP. The main difference has to do with the communication between View and ViewModel/Presenter:
- MVVM: when the ViewModel is modified, the View is updated by a library or framework. There's no way to update the View directly from the ViewModel, as it doesn't have this reference.
- MVP: The Presenter has a reference to the view so when a change is necessary, the presenter calls the view to explicitly make the change.
MVP 模式在安卓开发中可以不使用任何额外的支持库,也不需要其他的第三方类库,各层之间通过组合模式相互拥有所需要的实例,通过回调接口传递数据和处理逻辑,以达到让View层只专注于界面显示,P层负责在处理逻辑并作为View与Model的桥梁。
MVVM模式在安卓中的实现,需要使用官方提供的android.databinding库,当然android.databinding库也可以使用在MVP模式里,MVP模式可以结合android.databinding库使用,也可以不使用,但MVVP模式一定要使用android.databinding库。
根据官方的说明,MVP与MVVP的最大区别在于MVP模式里,P层以拥有View层的引用,当需要更新View时,P层通知View层更新界面,而MVVP模式里,ViewModel层不再拥有View的引用,View的更新和数据绑定通过android.databinding自动实现。