ViewModels In Android

Updated 31 January 2024

Save
ViewModels In Android

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.

1. Create ViewModel Class

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

2. Creating ViewModel Providers Object

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

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.

3. Creating ViewModel objects and Observing the changes

After creating the ViewModel object, we will register an observer. So that, whenever data changes in the ViewModel it will reflect the main class.

Conclusion

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.

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home