The library that we are going to talk about in this blog is
ViewModel from the official architecture component,
dagger-android for managing dependency injection. If you want to learn
dagger-android in a quick and easy way, I’ve got a blog covered.
Even you use things like
dagger to handle dependencies, you need to know that you ALWAY use
ViewModelProviders.of().get() to get the instance of your view model. It will manage the life cycle of a view model for you.
With this in mind, let’s start.
This one is quite easy. You create this method in your
Then use it like this:
T will be inferred from the left side.
In this case, you need to create
ListViewModel(val listStore:ListStore), but
ListStore is in
dagger, how you do that?
Well, first, we always use
ViewProviders to manage view model. So, we need to find another way to handle the customization phase of the view model, here we will inject a view model factory to do the trick.
Create the ViewModelFactory in a separate file:
Then in your
fragment, create the ViewModelFactory and inject it.
Here, we only inject the
ViewModelFactory, not the
Let’s say that your
ViewModel need a dependency named
listStore which is under
dagger‘s management. This is how you declare it:
You have to
@inject the dependencies from the constructor according to this line:
@Inject lateinit var viewModelFactory: ViewModelFactory<ListViewModel>. Because the constructor of
ListViewModel will be invoked during the
injection of the
Then, in your activity,
We can still re-use the
getViewModel()?! Of course, you can’t.
It’s a just another overload version of
This case is for where your
ViewModel needs some dependencies which are not under
dagger‘s management. Something like this:
ListViewModel needs to get
listId when it is initialized. How to do this?
First, we need a
It’s the same method as before with a slightly different signature.
And that famous
getViewModel() is back:
Then you can use it like this:
That’s it. Now you get it. Hope it helps.