如何在 Kotlin 中使用 Koin 注入 ViewModel?

Arc*_*nes 8 android kotlin android-viewmodel koin

我们如何使用 Koin 为 ViewModel 注入依赖项?

所以例如,我有一个ViewModel这样的:

class SomeViewModel(val someDependency: SomeDependency, val anotherDependency: AnotherDependency): ViewModel()
Run Code Online (Sandbox Code Playgroud)

现在这里的官方文档指出,要提供一个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() }
}
Run Code Online (Sandbox Code Playgroud)

然后注入它,我们可以这样做:

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()
    }
}
Run Code Online (Sandbox Code Playgroud)

对我来说令人困惑的部分是,通常你需要一个ViewModelFactory来提供ViewModel依赖项。这里是哪里ViewModelFactory?不再需要了吗?

Cor*_*zio 5

您好 viewmodel() 它是一个域特定语言 (DSL) 关键字,可帮助创建 ViewModel 实例。

在官方文档的 [link][1] 中,您可以找到更多信息

viewModel 关键字有助于声明 ViewModel 的工厂实例。此实例将由内部 ViewModelFactory 处理,并在需要时重新附加 ViewModel 实例。

这个 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() } 
} 
Run Code Online (Sandbox Code Playgroud)