KOIN 图重组时,委托函数 viewmodel() 不刷新 viewmodel 实例

When KOIN graph reassembling, delegate function viewmodel() not refreshing viewmodel instance

我们在我们的项目中使用 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() 调用时 - 一切都很好,图中的另一个实例正在刷新,但注入 activity 的 ViewModels - 不是,它们保留旧引用。我想,该视图模型附加到 activity 生命周期,可以帮助 activity 娱乐,但我认为这不是最好的解决方案。

有没有人遇到同样的问题?请帮我提供建议,请如何解决。

您可以使用 KOIN 中的作用域来做到这一点。

1) 在范围内定义您的 ViewModels

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

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

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

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

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

作用域关闭后,每当您请求创建或获取作用域时,它都会根据您的要求 return 新实例。

如需进一步参考,您可以参见下文link(第 8 点)。

Koin documentation