ViewModel observing data changes in other fragments

424 Views Asked by At

I have a items fragment which lists all the items and one other fragment which will use items list to create a sale document. I am using same viewModel for both of them when ever I filter items in items fragments, items in sale fragment are also filtered because data is observed in both fragments(This happens when I use activityViewModels for viewModel initialization). When I use viewModels for view model initialization then I am unable to share data in detail fragments for sale module.

1

There are 1 best solutions below

0
On BEST ANSWER

This is correct behaviour.

activityViewModels is tied to an activity lifecycle which outlives fragment. So if you replace / remove / add fragments in that activity your view model lives as long as the activity does.

viewModel initialization ties it to a fragment lifecycle. If you have 2 fragments on the same screen, you have 2 different view models too - these are 2 different objects. If you replace / add / remove fragments your view model dies with its fragment.