android - 如何在 Kotlin 中使用 Koin 注入(inject) ViewModel?

标签 android kotlin android-viewmodel koin

我们如何使用 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/

相关文章:

android - 有人可以解释一下 startActivity(intent) 和 startActivityForResult(intent) 是如何异步的吗?

kotlin - HOCON 配置文件动态替换

android - 我的doOnComplete在.Map完成之前被调用

android - Kotlin 和 Android 数据绑定(bind)

android - 如何在 Android 应用程序中共享 LiveData 实例?

android - Koin 2 在 Android 项目中创建功能范围的问题

java - 在 Android 应用程序中使用下载的 Java 类文件

android - 如何避免使用 AudioRecord 进行自动增益控制?

android - 同一 Activity 中的 webview 和 listview

android - Jetpack Compose 显示来自 viewmodel 的小吃吧 - 单场直播 Activity