Standard chat style app. Single-activity app with two fragments—one for the list of groups, another with a fragment to show the messages in the group. The two fragments are part of a nested nav graph so I can use navigation graph scope for my view models.
The ViewModel for the messages view needs the id of the messaging group so it can hit the API correctly. When the user taps one of the recycler view items on the message group list I attempt to create this ViewModel so the next fragment in the nav graph can use it:
// Try to create the ViewModel, with the custom factory so it can receive the message group id, on the destination fragment
val factory = MessagesViewModelFactory(item.group.id!!)
val chatVM: MessagesViewModel by navGraphViewModels(R.id.chat) { factory }
// Actually go to the next fragment, which is supposed to show all the messages for that group
val action = MessageGroupsFragmentDirections.actionNavigationSettingsToMessagesFragment()
this.findNavController().navigate(action)
In the onCreateView of the destination controller I do this to attempt to get the ViewModel:
val viewModel: MessagesViewModel by navGraphViewModels(R.id.chat)
which kills the app with this exception:
Caused by: java.lang.InstantiationException: > java.lang.Class<mycom.ui.messages.MessagesViewModel> has no zero argument constructor
Which is true, that constructor needs the message group id. However, that fragment (the messages one) does not know the message group id so I cannot create a new Factory... that's the whole reason I'm trying to instantiate it in the other fragment and reuse it in this fragment.
I guess my question is how am I supposed to retrieve a shared ViewModel, with a custom factory, in the destination fragment on the navigation graph?