android - When KOIN graph reassembling, delegate function viewmodel() not refreshing viewmodel instance
问题描述
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.
解决方案
您可以使用 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 点)。
推荐阅读
- laravel - 询问 laravel 刀片模板中的子视图
- boolean - 使用 DeMorgans 简化布尔表达式
- video - 在 windows server 2008 R2 上访问 mp4 文件说访问被拒绝
- c - 如何在 C 的 1 行中拆分字符串(字符)和变量?
- mongodb - Process.StandardInput.Write 未使用 .Net Core 写入 MacOS 上的终端
- spring-boot - spring-boot + kotlin + Junit中的单元测试POST API
- login - 如何使用 Jmeter 登录 LDAP?
- java - 我简单的 Java pi 计算器似乎总是给出无穷大?
- java - 为什么在 ViewModelProvider.Factory 实现中添加 @Singleton 注解会导致编译错误 [Dagger/MissingBinding]?
- javascript - HTTP500:在服务器上使用 ajax POST 但不是 localhost 时出现服务器错误