1

we are using in our project KOIN like DI library.

in some cases, when ViewModel instance not refreshing when Koin context is killing and recreating again. We need to implement feature like 'reassembling dependency graph in runtime', and this issue very critical for us.

I have ViewModel module like this:

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

And my graph is assembling in android application by this way:

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

And when reassembleGraph() is calling - all good, another instances in graph are refreshing, but ViewModels, that injected in activity - are not, and they are keeping old references. I guess, that viewmodel is attached to activity lifecycle, and could help activity recreation, but i think it's not the best solution.

Has anyone the same problems? And help me please with advice, how to solve it, please.

4

1 回答 1

3

您可以使用 KOIN 中的范围来完成。

1)在范围内定义您的 ViewModel

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 文档

于 2019-05-16T05:59:24.680 回答