Koin Sharedviewmodel With Savedstatehandle
I have single activity application and number of fragments. Some of these fragments are using my viewmodel, typically like this: private val myViewModel: MyViewModel by sharedViewM
Solution 1:
Update: as koin 2.1.6 is around, they introduced org.koin.androidx.viewmodel.ext.android.stateSharedViewModel
that you can use in your fragments.
Ok after an hour of digging Koin samples and figuring out a few gotchas:
- Assuming your view model is something similar to this:
classSavedStateViewModel(val handle: SavedStateHandle, val service: SimpleService)
- ...and your DI looks like this:
viewModel { (handle: SavedStateHandle) -> SavedStateViewModel(handle, get()) }
- Your shared state view model can be consumed in your fragments like this:
val sharedSaved: SavedStateViewModel bysharedViewModel()
- (important!) You need this declaration in your activity:
lateinitvar savedVm: SavedStateViewModel
- (important) You need to call this right after
super.onCreate(savedInstanceState)
in your activity:
savedVm = getStateViewModel()
It is important not to use lazy version for the above (stateViewModel).
Post a Comment for "Koin Sharedviewmodel With Savedstatehandle"