I want to provide some dependency at run time to ViewModel using Hilt. I have followed the solution that was directed by d.android.com this.
@HiltViewModel
public class ViewViewModel extends ViewModel {
...
@AssistedFactory
public interface ViewViewModelFactory {
ViewViewModel create(@Assisted int version);
}
@AssistedInject
public ViewViewModel(ProfileRepository repository, @Assisted int version) {
mProfileRepository = repository;
}
}
@AndroidEntryPoint
public class CarFragment extends Fragment {
@Inject
ViewViewModel.ViewViewModelFactory mViewViewModelFactory;
...
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
ViewViewModel viewModel = mViewViewModelFactory.create(21);
}
}
However, still getting the build error ViewModel constructor should be annotated with @Inject instead of @AssistedInject.
I am using hilt version 2.38.1 and AGP version 7.0.0. Also tried with some earlier version (2.35, 2.37).
I have also tried creating my own Factory Provider without any luck:
public class ViewViewModel extends ViewModel {
...
@AssistedFactory
public interface ViewViewModelFactory {
ViewViewModel create(@Assisted int version);
}
@AssistedInject
public ViewViewModel(ProfileRepository repository, @Assisted int version) {
mProfileRepository = repository;
}
public static ViewViewModel provideFactory(ViewViewModelFactory assistedFactory,
int version){
return new ViewViewModelFactoryProvider(assistedFactory,version).create(ViewViewModel.class);
}
public static class ViewViewModelFactoryProvider implements ViewModelProvider.Factory {
ViewViewModelFactory assistedFactory;
int version;
public ViewViewModelFactoryProvider(ViewViewModelFactory assistedFactory,
int version) {
this.assistedFactory = assistedFactory;
this.version = version;
}
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
return (T) assistedFactory.create(version);
}
}
}
@AndroidEntryPoint
public class CarFragment extends Fragment {
@Inject
ViewViewModel.ViewViewModelFactory mViewViewModelFactory;
...
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
ViewViewModel viewModel = ViewViewModel.provideFactory(mViewViewModelFactory,21);
}
}
@Inject
the error is:@Assisted parameters can only be used within an @AssistedInject-annotated constructor.
. When I switchInject
to@AssistedInject
the error is:ViewModel constructor should be annotated with @Inject instead of @AssistedInject
– Bennet