I'm trying to add the new Architecture Components ViewModel
to my application while injecting them with dagger. I based my code on what google showed here. I'm trying to avoid having a ViewModelFactory
for each ViewModel
type, so I used the ViewModelFactory
that receives Map<Class<? extends ViewModel>, Provider<ViewModel>> creators
. It works for ViewModels
that have dependencies with @Singleton
scope. However, one of my ViewModels
has a dependency that comes from the fragment. This is the module of that fragment:
@Module
public abstract class DownloadIssueDialogFragmentModule {
@Binds
abstract DialogFragment dialogFragment(DownloadIssueDialogFragment dialogFragment);
@Provides
@FragmentScope
static Issue provideIssue(DownloadIssueDialogFragment dialogFragment) {
return dialogFragment.getIssue();
}
}
And my ViewModelModule
:
@Module
public abstract class ViewModelModule {
@Binds
abstract ViewModelProvider.Factory bindViewModelFactory(ViewModelFactory factory);
@Binds
@IntoMap
@ViewModelKey(DownloadIssueViewModel.class)
abstract ViewModel bindDownloadIssueViewModel(DownloadIssueViewModel viewModel);
}
dagger says it can't provide Issue
. It makes sense since Map<Class<? extends ViewModel>, Provider<ViewModel>>
seems to be created at compile time. But I will only know the parameter during the scope of that fragment. How can I achieve this?
Thank you.
EDIT:
In the end I went with a different approach. Now I create a factory for each ViewModel and instead of injecting ViewModels, I inject the factory.
I created this library: AutoViewModelFactory
To automatically generate the factories. It's the best solution I've found so far.