Double instantiation of ViewModel loses arguments in SavedStateHandle #1940
Labels
status:checking
currently in analysis - discussion or need more detailed specs
status:wait_feedback
viewmodel
Milestone
Describe the bug
I am working on a KMP project where we are using Koin for the DI framework. There is no issue with Koin and the KMP side of the project, but there is one with the Android side.
When setting up a ViewModel with navigation arguments, Koin and the Compose Destinations navigation library, there seems to be a duplicate ViewModel instatiation that causes the application to crash. The crash occurs in the navigation library but is not caused by it.
Here is an extract from the logcat showing the issue:
As you can see, within less than 50 ms, I have one output indicating that I correctly retrieve the arguments from the
savedStateHandle
parameter of the ViewModel and another output indicating that it could not create an instance of my ViewModel (because it was missing arguments but this is a non-issue for me).What I believe is the root cause of the problem is that somewhere in the Koin framework (whether it is linked to the use of this navigation library or not I don't know), the ViewModel is being instantiated a second time but this time has no more arguments (since they were already retrieved in the first ViewModel instance).
A workaround I found is to use
single { ... }
instead ofviewModelOf(...)
orviewModel { ... }
. This alone makes me believe that the issue lies in the handling of ViewModel injection rather than the navigation library usedTo Reproduce
Steps to reproduce the behavior:
savedStateHandle
parameternavArgs
property from this libraryi. The implementation should look something like this:
val navArgs = savedStateHandle.navArgs<MyNavArgsDataClass>()
Expected behavior
I expect that when injecting a ViewModel with either DSL (
viewModelOf
orviewModel
), the ViewModel then provided via thekoinViewModel
Composable should not be recreated (or whatever is happening)Koin module and version:
koin-bom:3.5.6
koin-core
koin-android
koin-androidx-compose
Snippet or Sample project to help reproduce
All the necessary information to reproduce should be above.
Here are, however, the versions for the other potentially impactful libraries:
androidx-compose-bom:2024.06.00
androidx-compose-compiler:1.5.14
compose-destinations:1.10.2
kotlin:1.9.24
kotlinx-serialization:1.7.1
android-gradle-plugin:8.5.0
The text was updated successfully, but these errors were encountered: