KiranKala / ReactiveScorecard

Scorecard Application
0 stars 0 forks source link

ViewModelModule and Factory is tied to an specific viewModel class #2

Closed jmcaldera closed 6 years ago

jmcaldera commented 6 years ago

Factory should not return an specific viewModel class, it should be a generic one. This is achieved by providing a Map of viewModels to Factory's constructor and look for the one that is being requested.

To do this, we create a Module and make use of @Binds @IntoMap and we provide a custom key of type Class. Dagger will create the map and add every new viewModel we add to our this Module.

Since dagger creates the map, we should not be passing this manually to our Factory class, so @Inject annotation should be added to its constructor.

Also, factory should not have a Data Source dependency

Refer to: https://github.com/googlesamples/android-architecture-components/blob/master/GithubBrowserSample/app/src/main/java/com/android/example/github/viewmodel/GithubViewModelFactory.kt

https://github.com/googlesamples/android-architecture-components/blob/master/GithubBrowserSample/app/src/main/java/com/android/example/github/di/ViewModelKey.kt

https://github.com/googlesamples/android-architecture-components/blob/master/GithubBrowserSample/app/src/main/java/com/android/example/github/di/ViewModelModule.kt

Once this is done, we can perform a field injection of Factory class into our activity by using: @Inject ViewModelFactory viewModelFactory

KiranKala commented 6 years ago