如何将 Fragment 的参数项添加到 Koin 依赖图中?

Arc*_*nes 16 android dependency-injection kotlin koin

我有一个ViewModel它有它应该从采取的依赖Fragmentarguments

所以它是这样的:

class SomeViewModel(someValue: SomeValue)
Run Code Online (Sandbox Code Playgroud)

现在这个片段SomeValue在它的争论中收到了这样的:

class SomeFragment : Fragment() {
    val someViewModel: SomeViewModel by viewModel()

    companion object {
        fun newInstance(someValue: SomeValue) = SomeFragment().apply {
            arguments = bundleof("someKey" to someValue)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是我不知道如何添加SomeValueFragment's argumentsto Koin's 模块中获取的内容。

有没有办法让片段对 Koin 依赖图有所贡献?

Arc*_*nes 26

所以对于问同样问题的其他人,这里是答案:

https://doc.insert-koin.io/#/koin-core/injection-parameters

所以基本上,

你可以像这样创建你的模块:

val myModule = module {
    viewModel { (someValue : SomeValue) -> SomeViewModel(someValue ) }
}
Run Code Online (Sandbox Code Playgroud)

现在在您的片段中,您可以执行以下操作:

class SomeFragment : Fragment() {
    val someViewModel: SomeViewModel by viewModel { 
        parametersOf(argument!!.getParcelable<SomeValue>("someKey")) 
    }

    companion object {
        fun newInstance(someValue: SomeValue) = SomeFragment().apply {
            arguments = bundleof("someKey" to someValue)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 甚至更新的 URL https://insert-koin.io/docs/reference/koin-android/viewmodel#viewmodel-and-injection-parameters (4认同)
  • 新网址:https://doc.insert-koin.io/#/koin-core/injection-parameters (3认同)