koin icon indicating copy to clipboard operation
koin copied to clipboard

URGENT!!! (KoinViewModel doesn't scope properly for Lifecycle Changes on Android (For Kotlin Multiplatform)

Open TheArchitect123 opened this issue 1 year ago • 5 comments

Describe the bug Currently I'm trying to load a view model into a fragment, which is using android navigation. The issue here is that if I try to load a view model annotated with KoinViewModel, if the fragment/activity gets destroyed, and the lifecycle changes, the ViewModel recreates a new instance of itself, and it causes the whole process to break.

class MyViewModel : ViewModel() {
     
}

// Inside my fragment/activity
val viewModel = ViewModelCompat.getViewModel(this, MyViewModel::class.java)

// I tried this as well, same issue
val viewModel : MyViewModel by viewModels()

If I change orientation, or if the fragment gets destroyed, a new instance of MyViewModel gets recreated, and it causes an issue because the app has subscriptions/workers running on initialisation.

Expected behavior What I expect is that the view model itself survives configuration changes, across the lifecycle. However it's not been scoped properly, and I'm forced to use Singleton Annotations for ViewModels, and manually do cleanup/deinit for any resources

Koin module and version: implementation("io.insert-koin:koin-android:3.5.6") implementation("io.insert-koin:koin-core:3.5.6")

Snippet or Sample project to help reproduce This is a commercial project, so I can't upload the source code here.

TheArchitect123 avatar Aug 12 '24 20:08 TheArchitect123

This seems different in some aspect but also similar to my issue described in #1940. I'd be curious if you could confirm whether or not these two are similar since if they are, the root cause of both could be the same (making a fix simpler to identify and do)

MaxMichel2 avatar Aug 13 '24 09:08 MaxMichel2

The issue does look similar yes.

@MaxMichel2

TheArchitect123 avatar Aug 13 '24 16:08 TheArchitect123

@arnaudgiuliani

TheArchitect123 avatar Aug 14 '24 17:08 TheArchitect123

If you have any way to reproduce it (a sample project), this would clearly help me to fix this 👍

arnaudgiuliani avatar Aug 27 '24 10:08 arnaudgiuliani

val viewModel : MyViewModel by viewModels()

The main Google API is behaving the same way?

arnaudgiuliani avatar Aug 27 '24 15:08 arnaudgiuliani

Please reopen if needed

arnaudgiuliani avatar Nov 18 '24 12:11 arnaudgiuliani

Hello friend, have you found a solution to this bug, could you share it please?. I have the same issue right now.

alexanderommel avatar Dec 04 '24 17:12 alexanderommel