Android Jetpack: ViewModel
ViewModel is part of the Lifecycle library which was designed to help you solve common Android Lifecycle challenges and to make your apps more maintainable and testable.
A ViewModel holds your app’s UI data in a lifecycle conscious way that survives configuration changes. Separating your app’s UI data from your Activity and Fragment classes lets you better follow the single responsibility principle: Your Activities and Fragments are responsible for drawing data to the screen, while your ViewModel can take care of holding and processing all the data needed for the UI.
Making a ViewModel is simple:
* Adding the Lifecycle library to your build.gradle file
* Extending the ViewModel class
* Use ViewModelProviders to associate your ViewModel with your UI controller
Then you can move all of your UI related data into your new ViewModel. If you need to customize ViewModel construction, you can create a ViewModelProvider.NewInstanceFactory. ViewModels also work great with the LiveData class to create reactive UIs!
A few words of warning: don’t store Contexts in ViewModels and don’t confuse ViewModels with the onSaveInstanceState method.
For more information, check out the video and links below!
Gradle dependencies →
ViewModels – A Simple Example (Good place to start for very basic usage) →
ViewModel Documentation →
ViewModels – Persistence, onSaveInstanceState(), Restoring UI State and Loaders →
Architecture Blueprint sample with Lifecycle library
* Java →
* Kotlin →
Architecture Components samples →
ViewModels and LiveData Patterns and Antipatterns →
Example of ViewModel factory in sample app →
Architecture Components landing page →
Guide to app architecture →
Watch more Android Jetpack videos here →
Subscribe to the Android Developers channel here →
View more Technology: https://blogema.org/category/technology/