lateinit属性viewModelFactory尚未在Fragment中初始化

时间:2018-05-02 14:34:29

标签: android mvvm dependency-injection dagger-2 android-viewmodel

我在我的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

抽象类ViewModelModule {

@Binds
@IntoMap
@ViewModelKey(MainViewModel::class)
internal abstract fun bindsMainViewModel(mainViewModel: MainViewModel): ViewModel

 @Binds
    abstract fun bindViewModelFactory(factory: MyViewModelFactory): ViewModelProvider.Factory
}

ViewModelKey

    @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)
        }

    }
}

虽然我不太明白他们在做什么。

2 个答案:

答案 0 :(得分:0)

您可以尝试在onViewCreated()中启动吗?

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    mainViewModel = ViewModelProviders.of(this, viewModelFactory)
        .get(StationsViewModel::class.java)
    // binding.viewmodel = viewModel
}

应该没事的。

答案 1 :(得分:0)

也许您只是忘了像下面那样初始化ViewModelModule

@Module(includes = [ViewModelModule::class])
class AppModule(private val appContext: Context) 
// .....some code here
}

因为ViewModelModule提供了MyViewModelFactory实例