如何在 Kotlin 中使用 Koin 注入 ViewModel?
How to inject a ViewModel with Koin in Kotlin?
我们如何使用 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
在哪里?不再需要了吗?
你好 viewmodel() 它是一个域特定语言 (DSL) 关键字,可帮助创建 ViewModel 实例。
在此 [link][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() }
}
我们如何使用 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
在哪里?不再需要了吗?
你好 viewmodel() 它是一个域特定语言 (DSL) 关键字,可帮助创建 ViewModel 实例。
在此 [link][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() }
}