Shared ViewModel lifecycle for Android JetPack

后端 未结 2 1183
攒了一身酷
攒了一身酷 2021-02-08 15:53

The documentation https://developer.android.com/topic/libraries/architecture/viewmodel#sharing describes how we can share the same ViewModel across the different Fragments.

2条回答
  •  北海茫月
    2021-02-08 16:44

    Since you are using Android Jetpack, I can assume that you also use Navigation Component.

    If you want a ViewModel to only stay active when you are in certain fragments, you can create a navigation chart for those fragments, so that the shared ViewModel only lives while you are browsing between those fragments and is destroyed when you leave them.

    Imagine that your app has these fragments,

    • VehicleFragment: inside this fragment you have tabs(SedanFragment, PickupFragment, OffroadFragment, etc.)
    • UserProfileFragment
    • LoginFragment
    • etc.

    And you want to keep a ViewModel alive while you are browsing between Fragment Vehicles and its different tabs.

    Well, create a nested navigation chart for them like this.

    
    
    
        
            
        
    
        
            
                
                
                        
            
            
                ...
            
            
                ...
            
            
                ...
            
        
    
    

    Once you have created the nested navigation graph, simply request an instance of ViewModel using:

    private val mySharedViewModel: SharedViewModel by navGraphViewModels(R.id.myNestedGraph) {
        //defaultViewModelProviderFactory or the ViewModelProvider.Factory you are using.
    }
    

    You can find more details in this answer

提交回复
热议问题