Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Architecture Component: How to insert repository parameter

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?

like image 857
shshchch88 Avatar asked Jul 20 '17 04:07

shshchch88


1 Answers

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);
    }
}
like image 112
Entreco Avatar answered Sep 27 '22 17:09

Entreco