Assume a view model like this:
public class FooViewModel extends AndroidViewModel {
@Inject public FooViewModel(Application app, SavedStateHandle handle, Bar bar) {
// ...
}
}
I want to inject Bar
using Dagger 2. I am developing on Android.
According to the SavedStateHandle
docs:
You should use
SavedStateViewModelFactory
if you want to receive this object inViewModel
's constructor.
However, the SavedStateViewModelFactory
docs state that the factory is final
which means I cannot inject Bar
there, either.
So far, I have been injecting via a setter:
@Provides
FooViewModel provideFooViewModel(ViewModelStoreOwner owner, Bar bar) {
FooViewModel viewModel = new ViewModelProvider(owner).get(FooViewModel.class);
viewModel.setBar(bar);
return viewModel;
}
Is there a better way to do this?
I want to use constructor injection, mark the Bar
instance variable as final
and eliminate the setter.