我正在尝试在当前项目中实现MVVM模式。我的代码昨天工作正常。今天,当我更新Android Studio时,代码开始出现以下错误。
错误:[Dagger / MissingBinding]如果没有@Provides注释的方法,则无法提供java.util.Map,javax.inject.Provider>。
我已经检查了许多解决方案。大多数人说要在前端提供程序中使用@JvmSuppressWildcards。但这也无济于事。
以下是代码 ViewModelFactory
@Singleton
@Suppress("UNCHECKED_CAST")
class CustomViewModelFactory @Inject constructor(private val viewModelsMap: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>) :
ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
val creator = viewModelsMap[modelClass] ?: viewModelsMap.asIterable().firstOrNull {
modelClass.isAssignableFrom(it.key)
}?.value ?: throw IllegalArgumentException("unknown model class $modelClass")
return try {
creator.get() as T
} catch (e: Exception) {
throw RuntimeException(e)
}
}
}
ViewModelKey文件
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER)
@MapKey
annotation class ViewModelKey(val value: KClass<out ViewModel>)
ViewModule文件
@Suppress("unused")
@Module
abstract class ViewModelModule {
@Binds
@IntoMap
@ViewModelKey(HomeViewModel::class)
abstract fun bindHomeViewModel(homeViewModel: HomeViewModel):
ViewModel
}
AppComponent文件
@Singleton
@Component(
modules = [AndroidInjectionModule::class, ActivityBuilderModule::class, AppModule::class,
ApiRequestModule::class, PicassoModule::class, CompositeDisposableModule::class,
SchedulerModule::class, ApplicationContextModule::class, ViewModelModule::class,
ViewModelFactoryModule::class]
)
interface AppComponent {
@Component.Builder
interface Builder {
@BindsInstance
fun application(application: Application): Builder
fun build(): AppComponent
}
fun inject(app: FilmiReviewApp)
}