MVVM + Dagger2
我对Dagger非常陌生。我经历了许多示例项目并创建了这个项目。
我想知道的是使用下面的代码,如何将数据发送到特定的ViewModels。我知道如何通过创建特定的ViewModelProvider.Factory来做到这一点。但是,当我有通用的Factory类时,该怎么办。
ViewModelModule.Class
@Module
public class ViewModelModule {
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@MapKey
@interface ViewModelKey {
Class<? extends ViewModel> value();
}
@Provides
ViewModelFactory viewModelFactory(Map<Class<? extends ViewModel>, Provider<ViewModel>> providerMap) {
return new ViewModelFactory(providerMap);
}
@Provides
@IntoMap
@ViewModelKey(MyViewModel1.class)
ViewModel viewModel1(FetchDataUseCase1 fetchDataUseCase1) {
return new MyViewModel1(fetchDataUseCase1);
}
@Provides
@IntoMap
@ViewModelKey(MyViewModel2.class)
ViewModel viewModel2(FetchDataUseCase2 fetchDataUseCase2) {
return new MyViewModel2(fetchDataUseCase2);
}
}
ViewModelFactory.class
@Singleton
public class ViewModelFactory implements ViewModelProvider.Factory {
private final Map<Class<? extends ViewModel>, Provider<ViewModel>> creators;
@Inject
public ViewModelFactory(Map<Class<? extends ViewModel>, Provider<ViewModel>> creators) {
this.creators = creators;
}
@NonNull
@SuppressWarnings("unchecked")
@Override
public <T extends ViewModel> T create(@NonNull 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);
}
}
}
TIA