如何将 Fragment 的参数项添加到 Koin 依赖图中?
How to add a Fragment's argument item to Koin dependency graph?
我有一个 ViewModel
,它有一个依赖项,应该从 Fragment
的 arguments
中获取。
所以它是这样的:
class SomeViewModel(someValue: SomeValue)
现在该片段在其参数中收到了 SomeValue
,如下所示:
class SomeFragment : Fragment() {
val someViewModel: SomeViewModel by viewModel()
companion object {
fun newInstance(someValue: SomeValue) = SomeFragment().apply {
arguments = bundleof("someKey" to someValue)
}
}
}
问题是我不知道如何将从 Fragment
的 arguments
中获取的 SomeValue
添加到 Koin
的模块中。
有没有办法让片段对 Koin 依赖图做出贡献?
对于其他提出相同问题的人,这里是答案:
https://doc.insert-koin.io/#/koin-core/injection-parameters
所以基本上,
您可以像这样创建您的模块:
val myModule = module {
viewModel { (someValue : SomeValue) -> SomeViewModel(someValue ) }
}
现在在你的片段中,你可以做类似的事情:
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)
}
}
}
我有一个 ViewModel
,它有一个依赖项,应该从 Fragment
的 arguments
中获取。
所以它是这样的:
class SomeViewModel(someValue: SomeValue)
现在该片段在其参数中收到了 SomeValue
,如下所示:
class SomeFragment : Fragment() {
val someViewModel: SomeViewModel by viewModel()
companion object {
fun newInstance(someValue: SomeValue) = SomeFragment().apply {
arguments = bundleof("someKey" to someValue)
}
}
}
问题是我不知道如何将从 Fragment
的 arguments
中获取的 SomeValue
添加到 Koin
的模块中。
有没有办法让片段对 Koin 依赖图做出贡献?
对于其他提出相同问题的人,这里是答案:
https://doc.insert-koin.io/#/koin-core/injection-parameters
所以基本上,
您可以像这样创建您的模块:
val myModule = module {
viewModel { (someValue : SomeValue) -> SomeViewModel(someValue ) }
}
现在在你的片段中,你可以做类似的事情:
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)
}
}
}