【问题标题】:When KOIN graph reassembling, delegate function viewmodel() not refreshing viewmodel instanceKOIN图形重组时,委托函数viewmodel()不刷新viewmodel实例
【发布时间】:2019-04-19 08:05:55
【问题描述】:

我们在我们的项目中使用KOIN 类似 DI 库。

在某些情况下,当 Koin 上下文被杀死并再次重新创建时,ViewModel 实例不刷新。我们需要实现像'在运行时重新组装依赖图'这样的功能,这个问题对我们来说非常关键。

我有这样的 ViewModel 模块:

object ViewModelModule {
    val module by lazy {
        module {
            viewModel { AppLauncherViewModel(get(), get(), get(), get()) }           
            viewModel { AuthLoginPasswordViewModel(get(), get()) }
            viewModel { SettingsViewModel(get(), get()) }
            // some others
        }
    }
}

我的图表是通过这种方式在 android 应用程序中组装的:

    private fun assembleGraph() {
        val graph = listOf(
                AppModule.module,
                StorageModule.module,
                DatabaseConfigModule.module,
                RepositoryModule.module,
                InteractorModule.module,
                ViewModelModule.module
        )

        application.startKoin(application, platformGraph)
    }

    fun reassembleGraph() {
        stopKoin()
        assembleGraph()
    }

reassembleGraph() 正在调用时 - 一切都很好,图中的另一个实例正在刷新,但注入活动的 ViewModel 没有,它们保留旧的引用。我想,该视图模型附加到活动生命周期,并且可以帮助活动重新创建,但我认为这不是最好的解决方案。

有人遇到同样的问题吗?并请帮助我提出建议,如何解决它,请。

【问题讨论】:

    标签: android dependency-injection viewmodel android-architecture-components koin


    【解决方案1】:

    您可以使用 KOIN 中的范围来做到这一点。

    1)在范围内定义您的 ViewModels

    scope(named("ViewModelScope")){
        viewModel {
            AppLauncherViewModel(get(), get(), get(), get())
            AuthLoginPasswordViewModel(get(), get())
            SettingsViewModel(get(), get())
        }
    }
    

    2) 在您的应用程序类中使用以下行创建特定范围。

    val viewModelScope = getKoin().getOrCreateScope("ViewModelScope")
    

    以上代码用于获取 ViewModel。当你想重新创建范围时,你只需要关闭范围并重新创建。要关闭范围,请使用以下代码。

    val viewModelScopeSession = getKoin().getOrCreateScope("ViewModelScope")
    viewModelScopeSession.close()
    

    一旦范围关闭,那么在您请求创建或获取范围之后,它将根据您的要求返回新实例。

    如需进一步参考,您可以查看以下链接(第 8 点)。

    Koin documentation

    【讨论】:

      猜你喜欢
      • 2023-03-19
      • 2016-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 2013-12-27
      • 2020-04-10
      • 1970-01-01
      相关资源
      最近更新 更多