architecture - How to scope ViewModels properly? -


i trying wrap head around new android architecture components, viewmodel.

my impression fragment should not know activity or fragment owned by, can used in different contexts of application. examples seem contradict declaring viewmodel scope directly in fragment, rather fragment owner:

viewmodel = viewmodelproviders.of(getactivity()).get(someviewmodel.class); 

i able use fragment in master/detail configuration, both share same state (i.e. viewmodel instance), inside viewpager, fragments require separate state (i.e. separate viewmodel instances). expect fragment owner dictate scope, not seem supported approach.

a workaround came optionally pass in configured viewmodelprovider explicitly broaden scope of viewmodel if necessary (e.g. in master/detail configuration) , have separate viewmodels default:

final viewmodelprovider viewmodelprovider; if (viewmodelprovideroverride != null) {     viewmodelprovider = viewmodelprovideroverride; } else {     viewmodelprovider = viewmodelproviders.of(this); }  viewmodel = viewmodelprovider.get(someviewmodel.class); 

this way, owner can decide whether multiple fragments share state or not. haven't thought through yet, seems kind of fishy, since nothing close seems hinted @ in docs. feel missing obvious.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -