我们如何使用 Koin 注入(inject)具有依赖关系的 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() }
}
然后要注入(inject)它,我们可以这样做:
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
在哪里?不再需要了吗?
最佳答案
Hello viewmodel(),它是一个领域特定语言 (DSL) 关键字,可帮助创建 ViewModel 实例。
在官方文档的[链接][1]中,您可以找到更多信息
The viewModel keyword helps declaring a factory instance of ViewModel. This instance will be handled by internal ViewModelFactory and reattach ViewModel instance if needed.
此 koin 版本 2.0 [1] 的示例:https://insert-koin.io/docs/2.0/documentation/koin-android/index.html#_viewmodel_dsl
// Given some classes
class Controller(val service : BusinessService)
class BusinessService()
// just declare it
val myModule = module {
single { Controller(get()) }
single { BusinessService() }
}
关于android - 如何在 Kotlin 中使用 Koin 注入(inject) ViewModel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56284757/