我正在使用带有匕首2的多重绑定来注入视图模型。我必须在视图模型中使用构造函数注入,因此需要使用ViewModelProvider.Factory
注入视图模型。以下是我完成的配置
AppComponent.java
@Singleton
@Component(modules = {AndroidInjectionModule.class,
ActivityBuilderModule.class,
Bindings.class,
NetworkModule.class,
ViewModelModule.class})
public interface AppComponent {
void inject(App app);
}
ViewModelModule.java
@Module
public interface ViewModelModule {
@Binds
@IntoMap
@ViewModelKey(HomeScreenViewModel.class)
ViewModel homeScreenViewModel(HomeScreenViewModel homeScreenViewModel);
}
AppViewModelFactory.java
@Singleton
public class AppViewModelFactory implements ViewModelProvider.Factory {
private final Map<Class<? extends ViewModel>, Provider<ViewModel>> creators;
@Inject
public AppViewModelFactory(Map<Class<? extends ViewModel>, Provider<ViewModel>> creators) {
this.creators = creators;
}
@SuppressWarnings("unchecked")
@Override
public <T extends ViewModel> T create(Class<T> modelClass) {
Provider<? extends ViewModel> creator = creators.get(modelClass);
if (creator == null) {
for (Map.Entry<Class<? extends ViewModel>, Provider<ViewModel>> entry : creators.entrySet()) {
if (modelClass.isAssignableFrom(entry.getKey())) {
creator = entry.getValue();
break;
}
}
}
if (creator == null) {
throw new IllegalArgumentException("unknown model class " + modelClass);
}
try {
return (T) creator.get();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
HomeScreenViewModel.class
public class HomeScreenViewModel extends BaseViewModel {
@Inject
public HomeScreenViewModel(Repository repository) { // repository an Application scoped (@Singleton) dependency
mRepository = repository;
}
}
一切正常,当我想通过构造函数注入向该视图模型注入活动范围内的依赖项时,问题就开始了。
我有一些通过活动意图传递的参数,我想对其进行解析并将其作为依赖项传递给我的ViewModel。以下是使我的工作更加清晰的代码
ActivityBuilderModule.java
@Module
public abstract class ActivityBuilderModule {
@ContributesAndroidInjector(modules = {HomeScreenModule.class})
abstract HomeScreenActivity provideHomeScreenActivity();
}
HomeScreenModule.class
@Module
public class HomeScreenModule {
@Provides
public Bundle provideExtras(HomeScreenActivity homeActivity){
return homeActivity.getIntent().getExtras(); // say I'm extracting extras from activity intent and I need to supply it to viewmodel
}
}
我的ViewModel
就像
@Inject
public HomeScreenViewModel(Repository repository, Bundle bundle) {
mRepository = repository;
mBundle = bundle;
}
现在,它的抛出错误
error: [Dagger/MissingBinding] android.os.Bundle cannot be provided without an @Inject constructor or an @Provides-annotated method.
我知道出现错误是因为ViewModelProvider.Factory
是在应用程序范围内创建的单例组件,将无法注入活动范围内的此bundle
。有其他替代方法吗?现在,我在ViewModel
上添加了setter,并在创建ViewModel
之后手动设置了包。但我更喜欢在这里进行构造函数注入。有人知道该怎么做吗?