Problem Statement
While you are developing professional-level android apps, one of the most common things we need the consider is configuration changes. These configuration changes are Screen Rotations, Keyboard Changes, Language changes and Enable multi-window windows. Let us understand android ViewModel example.
The Android OS manages the lifecycle of activities, fragment
Let’s assume you have some Activity for showing the score of two players like below figure.
In this picture you show, We have used two buttons such as A and B. On these buttons, we have set onClickListener that will increase
As per activity lifecycle, while configuration changes happen activity has to destroy and recreate wi
ViewModel
ViewModel is
So ViewModel can hold value belong to the activity. As this diagram to the Google developer documentation shows from the movement app launches an activity, the activity appears on the screen. Activity has to pass three life cycle state create, start and resume. Activity has to pass onPause,onStop and onDestroy.
ViewModel starts on invoke onCreate methods. Through that time activity can recreate again and again but it instance will live in the memory holding activity data.
Summary of ViewModel
- Live through the configuration changes- If any configuration changes the data will live in ViewModel
- No worry about leak memory
- Data will be always updated – If API is calling data from
remote server the data will always update - Data will wait for you- If you call any APIs and that time you will rotate the phone and result delivered before activity recreation data will store in ViewModel and wait for the re-creation of activity
Step to Implementation ViewModel
I’m going to show you how to use ViewModel. It’s very easy you have to follow
- Add dependency in build.gradle
- Create a subclass of ViewModel
- Expose methods for data such as getInitialCount() and getCurrentCount() for both players.
- Write code in Activity
1. Add dependency in build.gradle
For implementing ViewModel Android example you have go to file menu and create a new project. open build.gradle and add below line of code
2. Create a subclass of ViewModel
Now create a new class with named is MainViewModel which extends ViewModel class and expose below methods.
3. Expose Methods
Now open MainActivity and add below line of code
Finally, following all these steps just RUN the project, The output will be as expected, the counter will not reset zero on configuration change, such as here.
This is a basic ViewModel Android example.
No comments:
Post a Comment