最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

why is my ViewModel not destroyed when i navigate back from a screen in kotlin multiplatform? - Stack Overflow

programmeradmin2浏览0评论

I am using koin and viewodel in my KMP project. I am using

val viewModel = koinViewModel<AddOrEditViewModel>()

to initialize my viewModel. Even when i go back from a screen and go to the same screen, i am still getting the 1st instance of the viewModel. I am expecting it to be destroyed when i go back from a screen. I tried

val key = Clock.System.now().epochSeconds.toString()
val viewModel = koinViewModel<AddOrEditViewModel>(key = key)

which didnt work. How can i make sure to get a new instance when i open a screen?? This is the libraries i use:

koinCore = "4.0.2"
koin-android = { module = "io.insert-koin:koin-android", version.ref = "koinCore" }
koin-androidx-compose = { module = "io.insert-koin:koin-androidx-compose", version.ref = "koinCore" }
koin-core = { module = "io.insert-koin:koin-core", version.ref = "koinCore" }
koin-compose = { module = "io.insert-koin:koin-compose", version.ref = "koinComposeMultiplatform" }
koin-test = { module = "io.insert-koin:koin-test", version.ref = "koinCore" }
koin-composeVM = { module = "io.insert-koin:koin-compose-viewmodel", version.ref = "koinCore" }

I am using koin and viewodel in my KMP project. I am using

val viewModel = koinViewModel<AddOrEditViewModel>()

to initialize my viewModel. Even when i go back from a screen and go to the same screen, i am still getting the 1st instance of the viewModel. I am expecting it to be destroyed when i go back from a screen. I tried

val key = Clock.System.now().epochSeconds.toString()
val viewModel = koinViewModel<AddOrEditViewModel>(key = key)

which didnt work. How can i make sure to get a new instance when i open a screen?? This is the libraries i use:

koinCore = "4.0.2"
koin-android = { module = "io.insert-koin:koin-android", version.ref = "koinCore" }
koin-androidx-compose = { module = "io.insert-koin:koin-androidx-compose", version.ref = "koinCore" }
koin-core = { module = "io.insert-koin:koin-core", version.ref = "koinCore" }
koin-compose = { module = "io.insert-koin:koin-compose", version.ref = "koinComposeMultiplatform" }
koin-test = { module = "io.insert-koin:koin-test", version.ref = "koinCore" }
koin-composeVM = { module = "io.insert-koin:koin-compose-viewmodel", version.ref = "koinCore" }
Share Improve this question asked Mar 17 at 10:39 hushed_voicehushed_voice 3,6263 gold badges38 silver badges73 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Well I feel soo stupid right now for wasting a whole day on this.

I had desktop and ios source along with android in my KMP project. And in my desktop actual viewModelModule i was using singleOf(::AddOrEditViewModel) instead of viewModelOf(::AddOrEditViewModel) which was why i was getting a singleton instance. I changed it and now its working as expected.

发布评论

评论列表(0)

  1. 暂无评论