【问题标题】:How to inject a ViewModel with Koin in Kotlin?如何在 Kotlin 中使用 Koin 注入 ViewModel?
【发布时间】: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


    【解决方案1】:

    Hello viewmodel() 它是一个领域特定语言 (DSL) 关键字,有助于创建 ViewModel 实例。

    在官方文档的这个 [链接][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() } 
    } 
    

    【讨论】:

    • 我明白了。那是我第一次看到该文档,非常感谢!
    • 你可以找到所有参考here
    • 现在可以找到文档here
    猜你喜欢
    • 1970-01-01
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-22
    相关资源
    最近更新 更多