I have a ViewModel that I create with parameters in a fragment:
val mViewModel: MemoViewModel = getViewModel {parametersOf(id)}
In that fragment's child fragments, I want to access that same ViewModel instance by way of Koin's getSharedViewModel feature:
val sharedViewModel: MemoViewModel = getSharedViewModel()
But this doesn't work because getSharedViewModel, as far as I can tell, is expecting that same id parameter.
Is there a way to inject a shared ViewModel without passing the initial parameters again?
It seems to me that, if you're sharing a ViewModel, you want to use that ViewModel as a way of passing data between fragments. Child fragments typically won't have the necessary parameters: they use the ViewModel to obtain them, no?
thanks
John
I think the problem is that getSharedViewModel uses the activity viewModelStore and you want to use the parentFragment viewModelStore.
try with this code in your child fragments :
val sharedViewModel: MemoViewModel = getSharedViewModel( from ={ parentFragment } )
For whomever gets here, I don't think the parentFragment answer is the answer at all. You 'just' have to pass in the injection params again, unfortunately.
For whomever gets here, I don't think the
parentFragmentanswer is the answer at all. You 'just' have to pass in the injection params again, unfortunately.
Is using parentFragment not meant to be used this way? Is there some side effect? Trying to clarify so I don't start using this incorrectly
I've been using the parentFragment solution since October, with no apparent side effects or crashes. I, too, would be keen to know why we shouldn't be doing it.
Perhaps there's a deprecation issue looming?
@surfsnowpro i agree too. i worry about lifecycle problem. anyone give me the answer what i have to use between fragment? i think scope is best choice but i want to inject viewmodel itself.
Most helpful comment
I think the problem is that getSharedViewModel uses the activity viewModelStore and you want to use the parentFragment viewModelStore.
try with this code in your child fragments :
val sharedViewModel: MemoViewModel = getSharedViewModel( from ={ parentFragment } )