You are on page 1of 11

Persisting UI State using

ViewModel
Android Mobile App
Radix Rascalia
Candra Bagus K.
Dwi Diana W.
M. Hanif A

2024
ViewModel
• The ViewModel class is a business logic or screen level state holder.
• It exposes state to the UI and encapsulates related business logic.
• Its principal advantage is that it caches state and persists it through configuration
changes.
• your UI doesn’t have to fetch data again when navigating between activities, or
following configuration changes, such as when rotating the screen.
• https://developer.android.com/topic/libraries/architecture/viewmodel?hl=en#java
The lifecycle of a ViewModel
ViewModel, how to import
• The ViewModel class comes from
an Android Jetpack library called
lifecycle-extensions
Adding a ViewModel
• select New → Java Class. Enter
QuizViewModel for the name.
• extend it to The ViewModel class
comes from an Android Jetpack
library called lifecycle-extensions
• In QuizViewModel.java, add a
constructor and override
onCleared(). Log the creation and
destruction of the QuizViewModel
instance.
Associating the ViewModel on Activity
• open MainActivity.java
• in onCreate(…), associate the
activity with an instance of
QuizViewModel.
• Run the apps
• Rotate the device
• The Activity is destroyed
• But the ViewModel survived
• Press the Back Button
• Now the ViewModel also
destroyed
Bibliography
• Sills, et. al., “Android Programming : The Big Nerd Ranch
Guide”, 5th Ed, 2023, Big Nerd Ranch.
• Smyth, “Android Studio Electric Eel Essentials – Java
Edition”, 2023, Payload Media.
Thank You ☺

You might also like