Is there a way to pass additional argument to my custom AndroidViewModel
constructor except Application context.
Example:
public class MyViewModel extends AndroidViewModel {
private final LiveData<List<MyObject>> myObjectList;
private AppDatabase appDatabase;
public MyViewModel(Application application, String param) {
super(application);
appDatabase = AppDatabase.getDatabase(this.getApplication());
myObjectList = appDatabase.myOjectModel().getMyObjectByParam(param);
}
}
And when I want to user my custom ViewModel
class I use this code in my fragment:
MyViewModel myViewModel = ViewModelProvider.of(this).get(MyViewModel.class)
So I don't know how to pass additional argument String param
into my custom ViewModel
. I can only pass Application context, but not additional arguments. I would really appreciate any help. Thank you.
Edit: I've added some code. I hope it's better now.
I made it a class in which the already created object is passed.
And then
For one factory shared between multiple different view models I'd extend mlyko's answer like this:
And instantiating view models:
With different view models having different constructors.
Why not do it like this:
and then use it like this in two steps:
(KOTLIN) My solution uses little bit of Reflection.
Lets say you don't want to create the same looking Factory class every time you create new ViewModel class which needs some arguments. You can accomplish this via Reflection.
For example you would have two different Activities:
And ViewModels for those Activities:
Then the magic part, Factory class's implementation:
You need to have a factory class for your ViewModel.
And when instantiating the view model, you do like this:
I wrote a library that should make doing this more straightforward and way cleaner, no multibindings or factory boilerplate needed, while working seamlessly with ViewModel arguments that can be provided as dependencies by Dagger: https://github.com/radutopor/ViewModelFactory
In the view: