【问题标题】:How to add a Fragment's argument item to Koin dependency graph?如何将片段参数项添加到加入依赖图?
【发布时间】:2019-06-04 02:39:34
【问题描述】:

我有一个 ViewModel,它有一个依赖项,应该取自 Fragmentarguments

所以它是这样的:

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

问题是我不知道如何将来自FragmentargumentsSomeValue 添加到Koin 的模块中。

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

【问题讨论】:

    标签: android kotlin dependency-injection koin


    【解决方案1】:

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

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

    【讨论】:

    • 非常感谢!!!您是否知道(对于上述情况)parametersOf(this) 是否可以使用?我不明白这个结构。是按名称映射还是应该在使用视图模型之前调用一些 setParameter?
    • 您能否进一步澄清您的问题,以便我更好地回答??
    • 但是如果 viewModel 也接收单个依赖项,比如存储库会是什么样子?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 2020-07-21
    相关资源
    最近更新 更多