Android MVVM — Do’s and Don’ts
Hello folks, I’m learning MVVM architecture with almost all Jetpack components, Dagger2, Retrofit & a few other libraries (I know I’m late 😄). While learning this I found a few ground rules which everyone follows or should follow. So, I’ve tried to accumulate some as per my understanding.
Since I’m new to all this, I may have done some mistakes. If you find any mistake in this, do comment below & teach me some MVVM. 😀
ViewModels should not hold any Android framework classes reference.
ViewModels shouldn’t import Android Framework classes. Make sure there are no android.* imports in your ViewModels. This improves testability, leak safety, and modularity.
import android.widget.TextView; //Referencing TextView from ViewModel
Views should not have any kind of logic, move it to ViewModel
Views should not have any kind of logic. Any conditional statements, loops & data manipulation should be done in ViewModel only. Move all your data logic from activities/fragments to ViewModel. This improves testability & modularity of code.
Never pass Views to ViewModels.
Fragments have different lifecycle than ViewModel. Views can be destroyed & recreated while ViewModel is fetching data from network unaware of recreation of view. Suppose data comes after some time and view reference might be destroyed or activity is not visible. This leads to a data leak or app crash.
Instead of passing Views to ViewModels, let the Views observe changes to it.
Passing Views to ViewModel is risky, use LiveData in ViewModel & observe data changes in Views. Using the observer pattern helps in configuration changes like device rotation, ViewModels persist over configuration changes, therefore, no need for fetching data again on configuration changes. (Note: Below given solution has 1 problem, I’ve explained it in next point)
Never pass fragment as LifeCycleOwener in LiveData
As shown in the previous point we pass
this (fragment) as LifeCycleOwner to observe LiveData changes. This implementation results in a growing number of observers on the same data if we call
onCreateView() or Later.
Data repository should be your single point of entry for data
As shown in the recommended app architecture you should add the repository as the single-point entry to your
- remote data
- local data (DB or files)
- cache data
Use Wrapper to provide information about your data
I use this wrapper class provided in jetpack documentation to get the status & other information like an error message.
You can use it as given below.
And in your Fragment/Activity observe live data & as per its status update the UI 😃
Please rate my post on the scale of 1 to 10 by hitting that many claps👏.
If you didn’t like any part of it or want to help me improve this, let me know in the comments section below I’ll try to work on it asap.
References / Additional Resources :
by the author.