Android Architecture Components ViewModel context issue -


i trying use new architecture components in android, , far has worked pretty well. however, have stumbled architectural problem.

i have mainactivity hosts bunch of fragments, a, b, , c. until now, every time need viewmodel (vm) fetch in context of mainactivity (like this: myviewmodel vm = viewmodelproviders.of(getactivity()).get(myviewmodel.class);). consider this:

  • fragment c lets user select value, , writes vm.
  • fragment a uses fragment c have user select value, , a reads value directly vm , shows in ui.
  • fragment b uses same approach fragment a.

the problem is, since vm in context of mainactivity, if fragment a has been used before b, value still available, , b show old data.

the obvious solution see create vm in contexts of fragments a , b respectively. cannot figure out how let fragment c access vms.

i create vm in context of fragment c, require fragments a , b create instance of c, don't think nice solution.

a third solution keep current approach , clear data in vm when appropriate, that's messy, think.

what nicest way go this?

you can have mapping in vm , store values a , b under different keys.

so, when a starts c passes a_key argument. when user chooses value in c, being stored in vm's map using a_key key. when a checks whether value available, checks value stored a_key.

the same b , b_key.


Comments

Popular posts from this blog

Sort a complex associative array in PHP -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -