我在我的 android 项目中使用 dagger 2(版本 2.15)进行依赖注入。除了注入 viewModelFactory 一切正常。我无法将它注入我的片段中。
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
private val mainViewModel: StationsViewModel by lazy {
ViewModelProviders.of(this, viewModelFactory)
.get(StationsViewModel::class.java)
}
我收到以下错误:
lateinit property viewModelFactory has not been initialized
我有 ViewModelModule:
@Module
abstract class ViewModelModule {
@Binds
@IntoMap
@ViewModelKey(MainViewModel::class)
internal abstract fun bindsMainViewModel(mainViewModel:
MainViewModel): ViewModel
@Binds
abstract fun bindViewModelFactory(factory: MyViewModelFactory):
ViewModelProvider.Factory
}
视图模型键
@MustBeDocumented
@Target(
AnnotationTarget.FUNCTION,
AnnotationTarget.PROPERTY_GETTER,
AnnotationTarget.PROPERTY_SETTER
)
@Retention(AnnotationRetention.RUNTIME)
@MapKey
annotation class ViewModelKey(val value: KClass<out ViewModel>)
和 ViewModelFactory
@Singleton
class MyViewModelFactory @Inject constructor(
private val creators: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
val creator = creators[modelClass] ?: creators.entries.firstOrNull {
modelClass.isAssignableFrom(it.key)
}?.value ?: throw IllegalArgumentException("unknown model class $modelClass")
try {
@Suppress("UNCHECKED_CAST")
return creator.get() as T
} catch (e: Exception) {
throw RuntimeException(e)
}
}
}
虽然我不太明白他们在做什么。