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
clets user select value, , writesvm. - fragment
auses fragmentchave user select value, ,areads value directlyvm, shows in ui. - fragment
buses same approach fragmenta.
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
Post a Comment