Android Architecture Components ViewModel context issue

408 views Asked by At

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 the VM.
  • Fragment A uses fragment C to have the user select the value, and then A reads the value directly from VM and shows it in its UI.
  • Fragment B uses the same approach as fragment A.

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?

1

There are 1 answers

0
Vasiliy On BEST ANSWER

You can have a mapping in VM and store the values for A and B under different keys.

So, when A starts C it passes its A_key as an argument. When user chooses a value in C, it is being stored in VM's map using A_key as a key. When A checks whether a value is available, it only checks the value stored for A_key.

The same for B and B_key.