0% found this document useful (0 votes)
13 views

View Model

The document discusses the lifecycle of a ViewModel in Android, specifically when its onCleared() method is called, which occurs when the ViewModel is no longer needed, such as when the app goes into the background or an activity is finished. It also explains how to create and retrieve ViewModels, including the use of ViewModelProvider and ViewModelFactory for instances requiring constructor parameters. Additionally, it highlights the difference between ViewModel and AndroidViewModel, emphasizing the context-awareness of the latter.

Uploaded by

Yash Bhardwaj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

View Model

The document discusses the lifecycle of a ViewModel in Android, specifically when its onCleared() method is called, which occurs when the ViewModel is no longer needed, such as when the app goes into the background or an activity is finished. It also explains how to create and retrieve ViewModels, including the use of ViewModelProvider and ViewModelFactory for instances requiring constructor parameters. Additionally, it highlights the difference between ViewModel and AndroidViewModel, emphasizing the context-awareness of the latter.

Uploaded by

Yash Bhardwaj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

View Model Section Summary(Short Note)

When is the ViewModel's onCleared() called?


A ViewModel's onCleared() is called when the ViewModel is no longer
required.
It will be called when the app is put into the background and the app
process is killed in order to free up the system's memory.
When the user invokes finish() of an activity, its view model will be
cleared(). Also when we click on the back button, ViewModel of current
activity will be cleared (onCleared() will be invoked)

Inheritance from an interface with '@JvmDefault' members


Error.
Android Studio and JVM always update its versions. As a result of that
some of you may experience this error message.
Inheritance from an interface with '@JvmDefault' members is only allowed
with -Xjvm-default option
Don't worry . The solution is very simple. Just add below code part to the
end of android block of your app level build.gradle file and sync.
​ tasks.withType(org.jetbrains.kotlin.gradle.tasks.K
otlinCompile).configureEach {
​ kotlinOptions {
​ freeCompilerArgs += [
​ "-Xjvm-default=all",
​ ]
​ }
​ }

Exam Warriors: A Digital Library


New way to get an instance of ViewModel.
A new way to get an instance of view model have being introduced. (But
this method is not stable yet, might not work for many cases)
​ private val viewModel: MainActivityViewModel by
viewModels()
We need to add these dependencies to the gradle first.
For Activities.
​ implementation
'androidx.activity:activity-ktx:1.3.1'
For Fragments
​ implementation
'androidx.fragment:fragment-ktx:1.3.1'

●​ When we are using an android app, when a configuration change like


screen rotation happens, app has to destroy and recreate the activity
or fragment with new configurations.​
As a result of that, values(states) created during the running period of
the activity will also be destroyed.​

●​ The Android Jetpack View Model architecture component has been


introduced as a solution for the above problem. We can use a view
model object to safely keep and retrieve values(states) of that
activity. (Note: this only available during the run time of the app, if we
need a permanent data storage we need to use a database)​

Exam Warriors: A Digital Library


●​ As its name says, view model is a model for a view. We usually create
a view model for each activity.​

●​ A ViewModel’s onCleared() is called only when the app is put into the
background and the app process is killed in order to free up the
system’s memory.Therefore, lifecycle changes of activities and
fragments does not affect to their ViewModels.(Activities and
fragments may destroy and recreate, but view model will live
throughout the process)

Create a VIewModel class.


​ class MainActivityViewModel : ViewModel() {
​ ...........
​ ...........
​ ...........
​ }

Get an instance(object) of a ViewModel using ViewModel


provider.
​ private lateinit var viewModel:
MainActivityViewModel
​ override fun onCreate(savedInstanceState: Bundle?)
{
​ super.onCreate(savedInstanceState)
​ .......
​ viewModel =
ViewModelProvider(this).get(MainActivityViewModel:
:class.java)
​ .......
​ }

Create a ViewModelFactory.

Exam Warriors: A Digital Library


​ class MainActivityViewModelFactory(private val
startingTotal : Int) : ViewModelProvider.Factory {
​ override fun <T : ViewModel> create(modelClass:
Class<T>): T {
​ if
(modelClass.isAssignableFrom(MainActivityViewModel
::class.java)){
​ return
MainActivityViewModel(startingTotal) as T
​ }
​ throw IllegalArgumentException("Unknown
View Model Class")
​ }
​ }

Get an instance(object) of a ViewModel when using a


ViewModelFactory.
​ class MainActivity : AppCompatActivity() {
​ private lateinit var viewModel:
MainActivityViewModel
​ private lateinit var viewModelFactory:
MainActivityViewModelFactory
​ override fun onCreate(savedInstanceState:
Bundle?) {
​ .........
​ viewModelFactory =
MainActivityViewModelFactory(125)
​ viewModel =
ViewModelProvider(this,viewModelFactory).get(MainA
ctivityViewModel::class.java)
​ .........
​ }

Exam Warriors: A Digital Library


​ }
​ }

Frequently Asked Questions.

1) What is the difference between ViewModel() and


AndroidViewModel() ?
The AndroidViewModel class extends ViewModel class, so it has all the
same functionality.

The only added functionality for AndroidViewModel is that it is context


aware, when initializing AndroidViewModel we have to pass the application
context as a parameter.

AndroidViewModel is helpful if we require context to get a system service


or have a similar requirement(displaying a Toast message).

​ class MyAnViewModel(application: Application) :


AndroidViewModel(application) {
​ ........
​ ........
​ }
2) What is "ViewModelProvider" ?
We can not construct a ViewModel instance on our own. We need to use
the ViewModelProvider utility provided by Android to create instances of
ViewModels.

3) When do we need to create a ViewModelFactory class ?


ViewModelProvider can only instantiate ViewModels with no arg constructors.

Exam Warriors: A Digital Library


So, if the ViewModel has constructor parameters(arguments) , ViewModelProvider need
a little extra support to create instances of it.

We provide that extra support by creating a Factory class and passing its instance to the
ViewModelProvider.

4) When we are extending AndroidViewModel, since it should always has "application"


as a constructor parameter, do we need to use a ViewModelFactory ?
No, if the ViewModel created extending AndroidViewModel, does not have parameters
other than "application", we do not need to use a ViewModelFactory for that.

5) What is the onCleared() function of a ViewModel?


When a ViewModel object is no longer required, system will call to its onCleared()
function to destroy(clear) it.

It will be called when the app is put into the background and the app process is killed
in order to free up the

system's memory.

When the user invokes finish() of an activity, its view model will be cleared().

Also when we click on the back button, ViewModel of current activity will be cleared
(onCleared() will be invoked)

Exam Warriors: A Digital Library

You might also like