-
Notifications
You must be signed in to change notification settings - Fork 0
(MVVM) Model View View Model
Devrath edited this page Nov 30, 2023
·
10 revisions
- To overcome the drawbacks of MVC, MVP architecture modifications were done to segregate it to a better representation of architecture called Model-View-ViewModel.
- It is one of the very popular ways of structuring the android code.
- MVVM helps you to separate your code into many layers that let you have your own responsibilities.
- Code becomes more
readable,testable,maintainable. - The codebase stands the test of time.
Contents |
|---|
| MVVM block diagram |
| MVVM + Repository Pattern block diagram |
| Updates to view layer from view-model |
| Code Summary |
| Advantages |
- We can use
live datato update theviewfromview-model.
Content |
|---|
What is Live Data |
Communicating between view and view-model |
Communicating between view-model and the repository |
- LiveData is an observable data holder class.
- Unlike a regular observable,
LiveDataislifecycle-aware, meaning it respects thelifecycleof other app components, such asactivities,fragments, orservices. - This awareness ensures
LiveDataonly updates app componentobserversthat are in an activelifecycle state.
- When we want to call a method in
view-model, We call a public function in theview-modelthat delegates the control to therepository. - Once the data is retrieved from the
repository, we just update the `live-data in the view model. - When you update
live data, all theobserversof the `live-data are notified. - Since the
LiveDataobserver is present inactivity/fragment, Control is received inviewand we can update the view.
- Since the
view-modelhas access to the repository reference we can call the methods in the repository - We can have a
contractimplemented in the repository similar to ourMVPrepresentation to communicate between theview-modelandrepository. - Now if we want to send a
callbackfromrepositoryto theview-modeljust we use thecontract, the callback we which can be set in the repository using theinit()method inview-model.
- Since we are using
LiveDatato communicate betweenviewand theview-model- Ensures your UI matches your data state
- No memory leaks
- No crashes due to stopped activities
- No more manual lifecycle handling
- Always up to date data
- Proper configuration changes
- Sharing resources
- Most important advantage of using
view-modelbeing it can handle configuration changes, meaning even whenactivity/fragmentis destroyed and recreated theview-modelis not destroyed immediately meaning it can retain the date whose references are kept in theview-model. - If we use
AndroidViewModelinstead ofViewModelwe can have access to theandroid contextwhich can be handy sometimes but ideally we should not haveandroid contextinview model, It should be available only in theview. We can achieve this usingDI-dependency injectionfor context dependentsartifactsinview-modelandrepositoryetc.