Updated 31 January 2024
In this blog, we will learn ViewModels In Android and check how it works under the hood & how it can be used to store and manage UI-related data in a LifeCycle-aware manner.
ViewModel work in a LifeCycle-aware manner, what does that mean? ViewModel stores data only while the app is running and will destroy data when the app is killed or destroyed. The ViewModel scope stays alive throughout the activity & fragment lifecycle and only destroys when a component is associated with it destroy.
Let’s understand how we can implement ViewModels in our Applications for optimizing the code and storing UI-related data which can survive the orientation changes.
First of all, we will create MyViewModel class which extends ViewModel. In this class, we will add our business logic for performing any actions. In this dummy code, we are fetching user data from the repository(Server or Room DB) and will return to the main component which calls ViewModel.
You may use any of the repository systems, you can use the Room database for fetching the data and REST API calls for fetching the data or performing any operation
1 2 3 4 5 6 7 8 9 |
public class MyViewModel(val userId:Int) : ViewModel { var userList: MutableLiveData<MutableList<String>> = MutableLiveData() fun fetchData() { // block of code which fetches data from the repository and assign value to user data userList.value = data fetched from repository } } |
For accessing the ViewModel, we need the “ViewModelProvider” class object which returns the ViewModel if already created. And if it is not created then create the same and then return to the calling Activity or Fragment class.
ViewModelProider constructor takes two arguments for creating its object which is as follows
1. ViewModelStoreOwner => Which stores the ViewModels, our activity or fragments works as ViewModelStore owner. As ComponentActivity(Parent class of Activity) implements ViewModelStoreOwner interface which has only one method as mentioned below
1 2 3 4 5 6 7 8 9 |
public interface ViewModelStoreOwner { /** * Returns owned {@link ViewModelStore} * * @return a {@code ViewModelStore} */ @NonNull ViewModelStore getViewModelStore(); } |
2. Factory
When you don’t provide a factor class then ViewModelProvider auto creates the same. But if you want to send some additional parameters in the ViewModel class then you need to create your own factory Class. The main purpose of this class is to send additional arguments or data to the ViewModel constructor.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class MainViewModelFactory (private val userId: Int) : ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(MyViewModel::class.java)) { return MainViewModel(userId) } throw IllegalArgumentException("Unknown ViewModel class") } } // example of creating ViewModelProvider object var viewModelProvider= ViewModelProvider(this,MainViewModelFactory).get(MyViewModel::class.java); |
1 2 3 |
mainViewModel=ViewModelProvider(this,MainViewModelFactory).get(MyViewModel::class.java); -------OR------- mainViewModel=viewModelProvider.get(MyViewModel::class.java) |
After creating the ViewModel object, we will register an observer. So that, whenever data changes in the ViewModel it will reflect the main class.
1 2 3 4 5 6 7 |
mainViewModel.userData.observe( viewLifecycleOwner, Observer { data: List<UserData> -> if (data.isEmpty()) showEmptyUI() else showDataView(data) } ) |
We talked about ViewModels In Android in this blog.
I hope it will aid in your comprehension and provide you with a basic understanding of it.
You may also read the Developer Console for additional information.
I appreciate your reading.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.