所以我是 Dagger 2 依赖注入的新手。我创建了一个自定义 ViewModelFactory 类,它返回我的 ViewModel。
@Singleton
public class CustomViewModelFactory implements ViewModelProvider.Factory {
private final MyCatchesRepository repository;
@Inject
public CustomViewModelFactory(MyCatchesRepository repository) {
this.repository = repository;
}
@NonNull
@Override
@SuppressWarnings("unchecked")
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
if (modelClass.isAssignableFrom(MyCatchViewModel.class)) {
return (T) new MyCatchViewModel(repository);
} else {
throw new IllegalArgumentException("ViewModel Not Found");
}
}
}
CustomViewModel
接受 a在MyCatchesRepository
构造函数中,然后创建MyCatchViewModel
. 我怎么能改变这个类,以便我可以使用这个 ViewModelFactory 来创建具有不同构造函数参数(存储库)的不同 ViewModel
这是创建 CustomViewModelFactory 的模块
@Module
public class RoomModule {
private final MyDatabase myDatabase;
public RoomModule(Application application) {
this.myDatabase = Room.databaseBuilder(application,
MyDatabase.class, AppConstants.DATABASE_NAME)
.build();
}
@Provides
@Singleton
MyCatchesRepository provideCatchesRepository(MyCatchDao myCatchDao) {
return new MyCatchesRepository(myCatchDao);
}
@Provides
@Singleton
MyCatchDao providesCatchDao(MyDatabase myDatabase) {
return myDatabase.myCatchDao();
}
@Provides
@Singleton
LuresRepository provideLureRepository(LureDao lureDao) {
return new LuresRepository(lureDao);
}
@Provides
@Singleton
LureDao provideLureDao(MyDatabase myDatabase) {
return myDatabase.lureDao();
}
@Provides
@Singleton
MyDatabase provideDatabase(Application application) {
return myDatabase;
}
@Provides
@Singleton
ViewModelProvider.Factory provideCatchesViewModelFactory(MyCatchesRepository catchesRepository) {
return new CustomViewModelFactory(catchesRepository);
}
}
视图模型模块
@Module
public abstract class ViewModelModule {
@Binds
@IntoMap
@ViewModelKey(MyCatchViewModel.class)
abstract ViewModel myCatchViewModel(MyCatchViewModel myCatchViewModel);
@Binds
@IntoMap
@ViewModelKey(FishingSpotViewModel.class)
abstract ViewModel fishingSpotViewModel(FishingSpotViewModel fishingSpotViewModel);
@Binds
abstract ViewModelProvider.Factory bindCustomViewModelFactory(CustomViewModelFactory customViewModelFactory);
}