【发布时间】:2019-12-29 22:42:07
【问题描述】:
Dagger 版本是 2.25.2。
我有两个 Android 项目模块:core 模块和app 模块。
在core模块中,我为匕首定义了CoreComponent,
在app 模块中我有AppComponent 用于匕首。
CoreComponet 在核心项目模块中:
@Component(modules = [MyModule::class])
@CoreScope
interface CoreComponent {
fun getMyRepository(): MyRepository
}
在核心项目模块中,我有一个存储库类,它不属于任何 dagger 模块,但我在其构造函数旁边使用 @Inject 注释:
class MyRepository @Inject constructor() {
...
}
我的应用组件:
@Component(modules = [AppModule::class], dependencies = [CoreComponent::class])
@featureScope
interface AppComponent {
fun inject(activity: MainActivity)
}
在MainActivity:
class MainActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val coreComponent = DaggerCoreComponent.builder().build()
DaggerAppComponent
.builder()
.coreComponent(coreComponent)
.build()
.inject(this)
}
}
我的项目是MVVM架构,总的来说:
MainActivity主机MyFragmentMyFragment引用了MyViewModelMyViewModel具有依赖关系MyRepository(如上所述MyRepository在core模块中)
这里是MyViewModel:
class MyViewModel : ViewModel() {
// Runtime error: lateinit property repository has not been initialize
@Inject
lateinit var repository: MyRepository
val data = repository.getData()
}
MyViewModel 在 MyFragment 中初始化:
class MyFragment : Fragment() {
lateinit var viewModel: MyViewModel
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)
...
}
}
当我运行我的应用程序时,它会因运行时错误而崩溃:
kotlin.UninitializedPropertyAccessException: lateinit property repository has not been initialize
该错误告诉我 dagger 依赖注入不适用于我的设置。那么,我错过了什么?如何摆脱这个错误?
==== 更新 =====
我试过了:
class MyViewModel @Inject constructor(private val repository: MyRepository): ViewModel() {
val data = repository.getData()
}
现在当我运行应用程序时,我得到了新的错误:
Caused by: java.lang.InstantiationException: class foo.bar.MyViewModel has no zero argument constructor
====== 更新 2 =====
现在,我创建了MyViewModelFactory:
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)
}
}
}
我将 MyFragment 更新为:
class MyFragment : Fragment() {
lateinit var viewModel: MyViewModel
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
override fun onAttach(context: Context) {
// inject app component in MyFragment
super.onAttach(context)
(context.applicationContext as MyApplication).appComponent.inject(this)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// I pass `viewModelFactory` instance here, new error here at runtime, complaining viewModelFactory has not been initialized
viewModel = ViewModelProviders.of(this, viewModelFactory).get(MyViewModel::class.java)
...
}
}
现在我运行我的应用程序,出现新错误:
kotlin.UninitializedPropertyAccessException: lateinit property viewModelFactory has not been initialized
还缺少什么?
【问题讨论】:
-
首先,您在视图模型的初始化过程中尝试使用
repository。到那时,该属性不可能已经被注入。您必须将其注入构造函数或懒惰地初始化data,例如使用lazy委托。其次,如何创建MyViewModel实例? -
@jsamol ,我用
MyFragment更新了我的问题,它显示了我是如何创建MyViewModel实例的。您能否给出一个代码示例作为您的答案? -
您在片段中声明视图模型时是否尝试添加注释
@Inject?
标签: android kotlin dagger-2 kotlin-android-extensions