MVVM Learning Note

Difference between MVP and MVVM:

If the MVP pattern meant that the Presenter was telling the View directly what to display, in MVVM, ViewModel exposes streams of events to which the Views can bind to. Like this, the ViewModel does not need to hold a reference to the View anymore, like the Presenter is. This also means that all the interfaces that the MVP pattern requires, are now dropped.

because both of them do a great job in abstracting the view’s state and behavior. The Presentation Model abstracts a View independent from a specific user-interface platform, whereas the MVVM pattern was created to simplify the event driven programming of user interfaces.

简单来说,就是 MVP 需要定义一组接口,V需要持有P的引用,P也需要持有V的引用,因为持有的是接口,所以P可以更新view,同时也和平台无关,即可以做 JUnit test。

但 MVVM 不需要定义这样一组接口,虽然 ViewModel 不需要像 Presenter 一样持有 View 的引用,但是 ViewModel 需要根据 view 定义并维护一组包含 View UI state 的 observable stream(这是最关键的),然后 View 才可以通过持有 ViewModel 的引用,订阅这些 stream 并更新视图。

ViewModel to expose states for the list of articles view, and handle all user actions.

  • Ask data from repository {@link ArticlesViewModel#mRepository}, and then construct the source data to view data which contains UI state.

  • Expose streams for view to subscribe the UI state, such as {@link ArticlesViewModel#getUiModel()}, {@link ArticlesViewModel#getLoadingIndicatorVisibility()}

  • Expose public methods for view to handle user actions, such as force pull-refresh {@link ArticlesViewModel#forceUpdateArticles()}

  • For user action in the sub-view, such as click or check in the list view item, define {@link Action} and implement the action {@link ArticlesViewModel#handleArticleTaped(Article)}, and pass to sub-view model {@link ArticleItem#ArticleItem(Article, Action)}

Ref

[1] https://medium.com/upday-devs/android-architecture-patterns-part-3-model-view-viewmodel-e7eeee76b73b, [2] http://upday.github.io/blog/mvvm_rx_common_mistakes/