Scoping a viewmodel to multiple fragments (not activity) using the navigation component

前端 未结 3 1790
北荒
北荒 2020-12-05 19:24

I\'m using the navigation component, I want a view model to be shared between a few fragments but they should be cleared when I leave the fragments (hence not scoping them t

3条回答
  •  我在风中等你
    2020-12-05 20:08

    so when i posted this the functionality was there but didn't quite work as expected, since then i now use this all the time and this question keeps getting more attention so thought i would post an up to date example,

    using

    //Navigation
    implementation "androidx.navigation:navigation-fragment:2.2.0-rc04"
    // Navigation UI
    implementation "androidx.navigation:navigation-ui:2.2.0-rc04"
    

    i get the view model store owner like this

    private ViewModelStoreOwner getStoreOwner() {
    
            NavController navController = Navigation
                    .findNavController(requireActivity(), R.id.root_navigator_fragment);
            return navController.getViewModelStoreOwner(R.id.root_navigator);
    }
    

    im using the one activity multiple fragments implementation, but using this i can effectively tie my view models to just the scoped fragments and with the new live data you can even limit that too

    the first id comes from the nav graphs fragment

    
      
    
        
    
      
    

    and the second comes from the id of the nav graph

      
      
    

    and then you can use it like so

    private void setUpSearchViewModel() {
        searchViewModel = new ViewModelProvider(getStoreOwner()).get(SearchViewModel.class);
    }
    

提交回复
热议问题