简体   繁体   English

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

[英]How to add a Fragment's argument item to Koin dependency graph?

I have a ViewModel which has a dependency which should be taken from the Fragment 's arguments .我有一个ViewModel ,它有一个依赖项,它应该取自Fragmentarguments

So its something like:所以它是这样的:

class SomeViewModel(someValue: SomeValue)

now the fragment recieves the SomeValue in its arguemnt like so:现在的片段临危的SomeValue在其arguemnt像这样:

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

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

problem is I don't know how to add SomeValue thats taken from the Fragment 's arguments to Koin 's module.问题是我不知道如何添加SomeValue取自这就是Fragmentarguments ,以Koin的模块。

Is there a way to make the fragment contribute to the Koin Dependency Graph?有没有办法让片段对 Koin 依赖图有所贡献?

So for anyone else asking the same question, here is the answer:所以对于问同样问题的其他人,这里是答案:

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

So basically,所以基本上,

you could create your module like so:你可以像这样创建你的模块:

val myModule = module {
    viewModel { (someValue : SomeValue) -> SomeViewModel(someValue ) }
}

Now in your fragment, you could do something like:现在在您的片段中,您可以执行以下操作:

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)
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM