I am trying to use the new Architecture Components in Android, and so far it has worked pretty well. However, I have stumbled into an architectural problem.
I have a MainActivity
that hosts a bunch of fragments, A
, B
, and C
. Until now, every time I need my ViewModel (VM) I fetch it in the context of MainActivity
(like this: MyViewModel vm = ViewModelProviders.of(getActivity()).get(MyViewModel.class);
). Now consider this:
- Fragment
C
lets the user select some value, and writes it to theVM
. - Fragment
A
uses fragmentC
to have the user select the value, and thenA
reads the value directly fromVM
and shows it in its UI. - Fragment
B
uses the same approach as fragmentA
.
The problem is, that since the VM
is always in the context of the MainActivity
, if fragment A
has been used before B
, the value will still be available, and B
will show some old data.
The most obvious solution that I see is to create the VM
in the contexts of fragments A
and B
respectively. But then I cannot figure out how to let fragment C
access those VM
s.
I could also create the VM
in the context of fragment C
, but that would require fragments A
and B
to create an instance of C
, which I don't think is a nice solution.
A third solution would be keep the current approach and clear the data in the VM
when appropriate, but that's also messy, I think.
What is the nicest way to go about this?
You can have a mapping in VM and store the values for
A
andB
under different keys.So, when
A
startsC
it passes itsA_key
as an argument. When user chooses a value inC
, it is being stored in VM's map usingA_key
as a key. WhenA
checks whether a value is available, it only checks the value stored forA_key
.The same for
B
andB_key
.