Search code examples
androidkotlinandroid-viewmodelandroid-mvvmkoin

Unable to use shared state ViewModel in Koin 2.1.6


I'm using Koin 2.1.6 in my app module. Here are the artefacts I use

implementation "org.koin:koin-android:2.1.6"
implementation "org.koin:koin-core:2.1.6"
implementation "org.koin:koin-androidx-viewmodel:2.1.6"
implementation "org.koin:koin-androidx-fragment:2.1.6"

And Koin module is

val userModule = module {
   viewModel { (handle: SavedStateHandle) -> UserViewModel(get(), handle) }
}

class UserViewModel(
         val iService: IService, //injected from core module
         val handle: SavedStateHandle
) : ViewModel()

I use this ViewModel on UserFragment

private val viewModel: UserViewModel by stateViewModel()

UserFragment contains an internal fragment- UserUpdates, inflated from layout, shares the above ViewModel.

  <fragment android:name="UserUpdates"
            android:id="@id/fragment_user_updates"
            android:width="match_parent"
            android:height="wrap_content" />

On UserUpdates fragment, I set the ViewModel as follows

 private val viewModel: UserViewModel by stateSharedViewModel()

However, I found out that ViewModel instances generated are not shared. In fact they are created as new objects. Is there anything I miss out here?


Solution

  • I believe you need to use stateSharedViewModel (instead of stateViewModel you have right now)