【发布时间】:2019-05-24 01:25:51
【问题描述】:
我们如何使用 Koin 注入具有依赖关系的 ViewModel?
例如,我有一个ViewModel,就像这样:
class SomeViewModel(val someDependency: SomeDependency, val anotherDependency: AnotherDependency): ViewModel()
现在官方文档here 指出,要提供ViewModel,我们可以执行以下操作:
val myModule : Module = applicationContext {
// ViewModel instance of MyViewModel
// get() will resolve Repository instance
viewModel { SomeViewModel(get(), get()) }
// Single instance of SomeDependency
single<SomeDependency> { SomeDependency() }
// Single instance of AnotherDependency
single<AnotherDependency> { AnotherDependency() }
}
然后注入它,我们可以这样做:
class MyActivity : AppCompatActivity(){
// Lazy inject SomeViewModel
val model : SomeViewModel by viewModel()
override fun onCreate() {
super.onCreate()
// or also direct retrieve instance
val model : SomeViewModel= getViewModel()
}
}
对我来说令人困惑的部分是,通常你需要一个 ViewModelFactory 来为 ViewModel 提供依赖项。 ViewModelFactory 在哪里?不再需要了吗?
【问题讨论】:
标签: android kotlin android-viewmodel koin