Ad

Understanding MVVM Architecture In IOS

I have few questions in order to understand the MVVM architecture for ios as below -

  1. How Is Model different from the view-model? The model also has the data and why do we need to write and update the same properties in view-model (Repetitive code)?
  2. Creating two-way data binding between view and view-model can be good in form validation. Any other application except it?
  3. Should we use KVO to create 2 binding between view and view-model? Any disadvantages anyone experience so far?
  4. Should we put Networking(API data fetch) Code inside view-model?
Ad

Answer

I am assuming twitter as an enable, to answer your questions to best of my knowledge hope it helps

1) Yes, ViewModel and Model are different

Model - Represents the Domain Objects (Eg: “User” object which may contain id : Int, name : String, avartarURL : String, company : String, location : String, followers : [User], following: [User], etc… )

ViewModel - only represents objects that are represented in view (Eg: nameLabelText : String, profileImageURL : String ) assuming that UserDetailView only shows User name and avatar image. 

2) In all cases when you wanna present quick flow in UI, Eg: if you try to follow or unfollow a user, if you look in the UI, when you press the tap on follow or unfollow, the button changes to opposite state quickly(Follow -> Unfollow or UnFollow -> Follow), even thought API request is not finished yet. Because its for better user experience and these apis are less likely to fail.

  View -> ViewModel -> API service 

If 200 OK

 Model Gets Updated 
 ViewModel -> Model

If Api Failed

 ViewModel gets updated and Error message is triggered 
 ViewModel -> View 

3) never used KVO, But highly recommend you to look into/Consider RXCocoa and RXSwift. If you haven’t already.

4) There is nothing that says we shouldn’t, if the app is small and doesn’t have lots of domain logic, then handling API’s in Viewmodel is not so bad idea. But if the Domain logic is lot and has the opportunity of grow. I would say include a Business logic layer and a service for API, that way you won’t have method explosion in ViewModel and layers will be separate

Ad
source: stackoverflow.com
Ad