I am using Android's ViewModel lib and I want to inject a Navigator in a ViewModel which is scoped inside App, but my navigator is dependent of activity. I don't know how to inject it. I'll copy and paste some files here but my project can be found here and the files I mention is under 'app/src/main/java/app/vehiclemonitor/' + 'app/' or 'viewmodel' or 'features/home'
VmAppComponent.java
@Singleton
@Component(modules = {VMAppModule.class, VMApiServiceModule.class, SchedulerModule.class, ViewModelModule.class})
public interface VMAppComponent {
void inject(VMApp app);
HomeActivityComponent injectHomeActivity(BaseActivityModule module);
AddEditVehicleActivityComponent injectAddEditVehicleActivity(BaseActivityModule module);
}
ViewModelModule.class
@Module
public abstract class ViewModelModule {
@Binds
@IntoMap
@ViewModelKey(HomeViewModel.class)
abstract ViewModel bindHomeViewModel(HomeViewModel homeViewModel);
@Binds
abstract ViewModelProvider.Factory bindViewModelFactory(ViewModelFactory factory);
}
public class HomeViewModel extends ViewModel {
@NonNull
private HomeNavigator navigationProvider;
@NonNull
private BaseSchedulerProvider schedulerProvider;
@Inject
public HomeViewModel(@NonNull final BaseSchedulerProvider schedulerProvider) {
this.schedulerProvider = schedulerProvider;
}
// @Inject
// public HomeViewModel(@NonNull HomeNavigator navigationProvider, @NonNull BaseSchedulerProvider schedulerProvider) {
// this.navigationProvider = navigationProvider;
// this.schedulerProvider = schedulerProvider;
// }
void handleAddButtonClick() {
navigationProvider.addNewVehicle();
}
public void setNavigationProvider(final HomeNavigator navigationProvider) {
this.navigationProvider = navigationProvider;
}
}
First of all, this is a good question, a lot of developers had/have the same question and currently there isn't an official solution to this.
The only sure thing is:
A
ViewModelshould not have references to Activities or Views in general.
What you should do is reading all this thread in GitHub https://github.com/googlesamples/android-architecture-components/issues/63, a lot of solutions have been posted and probably there is at least one good for you.
About the link you posted on googlesamples and blueprint, their Navigator is not good as you can think. It's still an example app and probably they removed some complexity to make the sample easier to understand for a wider set of developers.
I think a better approach is the one provided in this sample repo which completely remove references to Activities. (It's made in Kotlin, I don't know if you can emulate the same behaviours with Java but you could try at least).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With