Home > other >  Shared ViewModel Not Working With Bottom Sheet Dialog Fragment, DB and UI
Shared ViewModel Not Working With Bottom Sheet Dialog Fragment, DB and UI

Time:11-25

i have a really simple vocabulary note app contains 2 fragment and 1 root activity. In HomeFragment i have a button "addVocabularyButton". When it is clicked a BottomSheetDialogFragment appears and user gives 3 inputs and with a viewmodel it is saved in DB. My problem is when i save the input to the DB it works fine but i cannot see in HomeFragment that word instantaneously. I have to re-run the app to see in home fragment. I am using Navigation library and recycler view in home fragment.

Github link : enter image description here enter image description here

CodePudding user response:

This is because multiple instances of the same View Model are created by the Navigation Library for each Navigation Screen.

You need to tell the Navigation Library to share the same ViewModel between all navigation screens.

Easiest way to fix this is to scope the viewModel to the Activity rather than a Fragment and using it in all your fragments.

val viewModel = ViewModelProvider(requireActivity()).get(MyViewModel::class.java)

This way, the viewModel is scoped to the Application instance rather than Fragment. This will keep the state in the viewModel persistent across the Application.

You can also do this by scoping the viewModel to the navigation graph.

val myViewModel: MyViewModel by navGraphViewModels(R.id.your_nested_nav_id)

Alternate method, if you're using dependency injection libraries

val navController = findNavController();

val navBackStackEntry = navController.currentBackStackEntry!!

If you use hilt, you can just pass your NavBackStackEntry of the NavGraph to hiltViewModel()

val viewModel = hiltViewModel<MyViewModel>(//pass NavBackStackEntry)

This will give you a viewModel that is scoped to NavBackStackEntry and will only be recreated when you pop the NavBackStackEntry(ie Navigate out of the navigation screens.)

  • Related