I am currently implementing a one Activity application with multiple fragments using Google's NavGraph, at the moment i have a Fragment inside the MainActivity that holds a ViewPager2 and inside 2 child Fragments for the tabs
Right now i have 1 ViewModel that holds the parent and child Fragments, when i initialize the ViewModel, instead of creating a single instance for all 3 Fragments, i get 1 instance per Fragment, how do i have only 1 instance?
this is how i init the ViewModel for the parent and child Fragments
paymentViewModel = ViewModelProvider(requireActivity()).get(PaymentViewModel::class.java)
shouldn't the ViewModelProvider return the already created instance if it already exists instead of duplicating?
The key here is the
context
passed in to theViewModelProvider
's contructor, so essentialy currently you're getting the vm provider of the activity, which should return the instance the activity is using.So yes, the snippet should work as I see, how are you instantiating the VM in the activity?