In a viewmodel class, I've seen sample codes where the constructor takes in a repository as a parameter. Like so:
public SampleViewModel(SampleRepository sampleRepository){
...
}
But in the activity, you use this line to create a viewmodel class ViewModelProviders.of(this).get(SampleViewModel.class)
. How do you pass a repository as a parameter to the viewmodel? I also come across mentioning of "dependency injection". Being an inexperience programmer, can anyone advice if DI is related to my question?
You have to supply a ViewModelProvider.Factory when you get your viewmodel.
ViewModelProviders.of(this, new SampleViewModelFactory(sampleRepo)).get(SampleViewModel.class)
Here's a sample:
class SampleViewModelFactory implements ViewModelProvider.Factory {
private final SampleRepository repo;
@Inject
public SampleViewModelFactory(SampleRepository repo) {
this.repo = repo;
}
@Override
public SampleViewModel create(Class modelClass) {
return new SampleViewModel(repo);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With