11

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

    }
}

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

4

2 回答 2

5

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

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

应该没问题。

于 2019-06-10T05:15:46.313 回答
0

也许你只是忘记像下一个那样初始化 ViewModelModule

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

因为 ViewModelModule 提供了 MyViewModelFactory 实例

于 2020-01-16T14:42:00.640 回答