I'm using Navigation Component + Hilt DI. I have a Navigation Destination Fragment which hosts a viewpager with 2 fixed fragments. What is the right way to Instantiate the ViewModels within those child fragments and scope it to the navigation destination? Currently we're using the following code
private val vm: ChildViewModel by hiltNavGraphViewModels(R.id.parentFragment)
private val cvm: ParentViewModel by hiltNavGraphViewModels(R.id.parentFragment)
However, this at times throws an IllegalArgumentException exception
java.lang.IllegalArgumentException: No destination with ID 2131363082 is on the NavController's back stack. The current destination is Destination(...)
Turns out I was navigating to another page immediately and popping this fragment from back stack. But the fragment wasn't immediately getting destroyed. Hence the exception was thrown if I accessed the viewmodel in that state. So to resolve it I simply did not use the viewmodel if I am to navigate to another place.