iammert / AndroidArchitecture

Recommended architecture by Android
888 stars 192 forks source link

ViewModel injection #1

Closed Galaxer closed 7 years ago

Galaxer commented 7 years ago

In MovieListFragment I see the following ViewModel injection, however I don't see where you're providing this dependency in any module. How are you injecting this?

@Inject
MovieListViewModel movieListViewModel;
iammert commented 7 years ago

This is how dagger works. When you do constructor injection in your class, You don't need to provide an instance. Dagger do it for you.

In this case, we provide repository instance in our appmodule. So we can inject into viewmodel by @inject annotation. Dagger checks constructor parameters in viewmodel and check module and provided instances if it can create an instance of that viewmodel. Is it clear?

Galaxer commented 7 years ago

Ok, but I thought the way to create the new ViewModel component so that it survives orientation changes and lives only until the activity/fragment is fully destroyed (documentation) was like following:

MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);

But wouldn't dagger create a new instance like the this?

new MovieListViewModel(movieRepository)

iammert commented 7 years ago

You are absolutely right. Future commits will solve this problem. ViewModelFactory class is created for that. I will implement that logic soon.

iammert commented 7 years ago

I will keep this open untill I fix this.

iammert commented 7 years ago

@Galaxer I fixed that issue. Now viewModels are injected by ViewModelSubComponent and ViewModelProvider.Factory. These classes is created based on googlesamples official architecture.