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
Clets the user select some value, and writes it to theVM. - Fragment
Auses fragmentCto have the user select the value, and thenAreads the value directly fromVMand shows it in its UI. - Fragment
Buses 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 VMs.
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
AandBunder different keys.So, when
AstartsCit passes itsA_keyas an argument. When user chooses a value inC, it is being stored in VM's map usingA_keyas a key. WhenAchecks whether a value is available, it only checks the value stored forA_key.The same for
BandB_key.