1

I have a navigation as follows:

FragmentList -> FragmentDetailA -> FragmentDetailB -> FragmentDetailC

I use a viewModel for the detail FragmentDetailViewModel

private val detailViewModel: DetailViewModel by activityViewModels()

But if I go forward, and then back, the above fragmentDetails are changed. How to have a viewmodel assigned to the fragment without changing the others?

Solution:

First of all, change activityViewModels() for viewModels()

Then, the problem was with setFragmentResultListener. It was called before instantiating the new fragment, then the call was made on Fragment A and not on Fragment B. I decided to pass data between destinations with Bundle objects.

Thanks a lot

Patrick
  • 1,629
  • 5
  • 23
  • 44
  • FYI the point of `by viewModels()` is that every instance of *the same class* gets the same `ViewModel` object, so the same data is shared between different instances. `by activityViewModels()` allows fragments to ask the current activity for **its** copy of a particular VM - it allows separate fragments in the same activity to access the same VM and share data/state. (There's a similar one in the Navigation library, `by navGraphViewModels()` which shares VM instances between everything in an entire navigation graph). When you want a Fragment to have its own unique data, use `by viewModels()` – cactustictacs Jan 01 '22 at 19:19

2 Answers2

2

With this way that you initialized view model, view model depends on the parent activity you must use this way

private val detailViewModel: DetailViewModel by viewModels()

to your view model instance depends on your fragment instance.

Mobin Yardim
  • 695
  • 7
  • 17
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 01 '22 at 09:09
1

It sounds like you want to link the viewmodel to the fragment.

ViewModelProvider(this,viewModelFactory).get(MyViewModel.class)
apxcode
  • 7,696
  • 7
  • 30
  • 41