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 sharedViewModel()
What if I want to have the model both shared
and keep its state with SavedStateHandle? I cannot figure out if this is supported and if so, how it needs to be used (declaring viewmodel as stateViewModel in hosting activity is not working).
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:
class SavedStateViewModel(val handle: SavedStateHandle, val service: SimpleService)
viewModel { (handle: SavedStateHandle) -> SavedStateViewModel(handle, get()) }
val sharedSaved: SavedStateViewModel by sharedViewModel()
lateinit var savedVm: SavedStateViewModel
super.onCreate(savedInstanceState)
in your activity:savedVm = getStateViewModel()
It is important not to use lazy version for the above (stateViewModel).