With the new
android.arch.lifecycle.ViewModel, you can extend your own ViewModel which is life cycle aware. Or you can use
AndroidViewModel if you want to inject
context to your model. One problem with the default
ViewModel is the constructor takes zero parameters. If you want to make it takes parameters, you need to make a new
FactoryClass for each view model. But with Kotlin, it could be more simple. Let’s see how to do it.
If you want your view model to have a constructor which takes a parameter like this
You need to create an according factory class like this:
And use it:
The previous way works, but you have to create many factory class like that which seems overkill. So a more elegant kotlin is like this:
And use it like this:
You can add that viewModelFactory to your
BaseActivity class so you can use it across apps.
Hope it helps.