I'm using the method proposed by <@U3FQZ0EGL> in m...
# koin
a
I'm using the method proposed by @cketti in my project now, but I'm having some problems with a shared viewmodel. In my setup itemId is read in the master fragment from the arguments passed to it.
model = getViewModel(parameters = { mapOf("itemId" to itemId) })
I'm sharing the viewmodel with the detail fragment so that (in theory) it only needs to load once. I tried
model = getSharedViewModel()
But it fails with:
Copy code
Caused by: org.koin.error.BeanInstanceCreationException: Can't create bean Factory[class=za.co.ruggedmobile.petermetertest.ui.meters.MetersViewModel, binds~(android.arch.lifecycle.ViewModel)] due to error :
    	kotlin.TypeCastException: null cannot be cast to non-null type <http://kotlin.Int|kotlin.Int>
a
it's ok then ?
a
No. I thought it was. I need a new VM per Master Fragment. I just noticed that it shares the same VM per activity, which in my case never changes,
So whatever gets loading in the
VM initially stays the same for the entire run of the app,
(Single activity App)
a
then use
by viewModel()
in your fragment
it will use its own instance
a
and in the nested fragment?
Maybe you mean use
getViewModel
in main fragment, and
by viewModel
in nested, is this right?
I'll try that out
a
If I understand, you want to share instance of VM between fragments only ?
a
yes.
I have fragment that reads from a DB based on an id passed to the viewmodel constructor. The other fragment is nested inside that one, and gives a different view on the same data (via other db calls). I've managed to get something working by passing the model to the nested fragment using
childFragmentManager
and a
setViewModel
method on the nested fragment, but that seems like a hack.
The nested fragment is embedding in the main fragment's layout.
Seems like I have my head screwed on backwards. It appears that the cleanest solution is to give the nested fragment it's own VM and using
childFragmentManager.findFragmentById
in the master fragment to pass the id down with a public setID() method on the nested fragment.
a
mhhh yes, is there any way to redesign it away from Fragments
a
Yes, it just happens to have been done like that as it came from an older project.