Room + ViewModel + LiveData + RecyclerView (MVVM) Part 5 – VIEWMODEL – Android Studio Tutorial
In part 5 of the Architecture Components tutorial, we will create our Viewmodel class.
The ViewModel works as a gateway between the UI controller and the repository. It stores and processes data for the activity/fragment and it doesn’t get destoyed on configuration changes, so it doesn’t lose it’s variable state for example when the device is rotated.
By extending AndroidViewModel, we get a handle to the application context, which we then use to instantiate our RoomDatabase.
In our activity we let the system provide us the correct ViewModel instance by calling ViewModelProviders.of, where we pass the Activity or Fragment this ViewModel’s lifecycle should be scoped to. When our Activity/Fragment is then destroyed, the ViewModel will go through it’s onCleared method and get removed from the memory.
In our activitie’s onCreate method, we retrieve the LiveData that is stored in our ViewModel and call observe on it, where we pass a LifecycleOwner and an Observer. In the onChange callback we get an update on our data whenever something in the corresponding database table changes. The LiveData will automatically start and stop sending updates to our activity at the right time in it’s lifecycle and clean up any unused references.
Watch the whole playlist:
Example code for this part:
https://gist.github.com/codinginflow/4d28adf5282a34a3bf8d945f5e1fa902
____________________
💻 Find the BEST programming tutorials on TutHub:
https://tuthub.io
⭐ Get my MVVM Caching Course now:
https://codinginflow.com/caching
❗ Subscribe to the channel:
https://www.youtube.com/c/codinginflo…
📨 Subscribe to the Coding in Flow newsletter:
https://codinginflow.com/newsletter
❓ Join our free developer community:
https://discord.gg/TSnMvmc
📣 Follow Coding in Flow on other sites:
Facebook: https://www.facebook.com/codinginflow
Instagram: https://www.instagram.com/codinginflow
TikTok: https://www.tiktok.com/@codinginflow
Twitter: https://twitter.com/codinginflow
Github: https://github.com/codinginflow
💰 Business requests, sponsoring, etc.: info@codinginflow.com
Views :134421
android studio