What is the viewmodel

  • A data store component with host lifecycle awareness
  • Viewmode stores data that persists after the page is destroyed and rebuilt due to configuration changes, using the same viewModel instance

When can viewModels be reused

  • Configuration changes such as: horizontal and vertical screen switch, resolution adjustment, permission change, system font style
  • If the page is recycled for system reasons such as low memory, low battery, etc. (savedState’s ability)

The use of the viewmodel

Use a

This viewModel can be done because of system reasons page destruction and reconstruction, so that the preservation of data, in fact, is the reuse of the ViewModel

class mViewModel:ViewModel() { val getHttp : MutableLiveData<T> fun getHttp():LiveData<T>{// If the page is destroyed due to a configuration change, the viewModel instance is saved // so gethttp.value has a value, If (getHttp. Value == null){data = api.gethttp () getHttp. Value = data} return getHttp}} class Activity { Mviewmodel.gethttp ().observer(this, observer {// get data})}Copy the code

Use two

This is no matter the configuration is insufficient, memory, power and other reasons cause the page to be recycled when rebuilding

It doesn’t matter if it’s the same viewModel instance

Need to introduce API 'androidx. Lifecycle: lifecycle - viewmodel - savedstate: 2.2.0' class mViewModel (val SavedState: SavedStateHandle) : the ViewModel () {val getHttp = MutableLiveData < T > ()/fun/level page getHttpData () {/ / data is returned, Memory level reuse, If (gethtt. value == null){gethttp.value = savedState.get<T>(Key) return getHttp} // No data val data = Api.gethttpdata () savedstate. set(Key,data) gethttp. value = data return getHttp}}Copy the code

Use three

Data sharing across pages

class MyApplication:Application(),viewModelStoreOwner {
   prvate val appViewModelStore :ViewModelStore by lazy{
       ViewModelStore()
   }
   
   override fun getViewModelStore(): ViewModelStore {
        return appViewModelStore
    }
}

// 创建 传applicaiton
val viewmodel = ViewProider(application).get(xxxViewModel::class.java)

Copy the code

How is viewModel reuse implemented?

Let’s start by creating the ViewModel

ViewModelProvider(this).get(xxxViewModel::class.java)
Copy the code

So the ViewModelProvider takes a ViewModelStoreOwner and a Factory that the system created for us

And our activity or Fragment implements the ViewModelStoreOwner interface and overwrites getViewModelStore to return a ViewModelStore object, so we can just pass this

And then take the two values that we passed inViewModelStoreandFactoryI made a save

And the ViewModelStore is essentially a HashMap that holds our ViewModel

Then see againgetThe method is to get the ViewModel from the ViewModelStore, or create it from the Factory

Since the ViewModel is stored in the ViewModelStore, the ViewModel exists as long as the ViewModelStore exists

So reuse of viewModel instances becomes reuse of viewModel Store

ViewModelStore is retrieved in the Activity, so go to Activity#getViewModelStore()

You can seeNonConfigurationInstancesIn the ViewModelStore

NonConfigurationInstances is used for the configuration changes when saving data to use, it also saved us ViewModelStore, then where is the store

You can search for a NonConfigurationInstance where does it come out new, because you have to get it to save itNonConfigurationInstance.viewModelStore = xxxTo save it, so I found itonRetainNonConfigurationInstanceMethod

This method is called in ActivityThread, which involves the activity destroying and rebuilding process. You can explore the process for yourself

SavedState capability, viewModel can not be the same instance of data reuse, how to do it?

Class diagrams for several important classes

Data Storage Process

Data Recovery Process

Data reuse process

In fact, SavedState is very simple, the above three pictures have all been described, and I don’t know how to explain it for the moment. I feel there is nothing to write after the code screenshots come out. If there is further research, I will write it later

Why use the ViewModel? What’s the point? Why is MVP ok? Why do we have to design the VM layer

  • In the traditional MVP, the P layer still has the View layer applied, and the P layer doesn’t know if the V layer has been destroyed. An asynchronous callback problem is involved, but in MVVM mode, the V layer relies on the VM layer, and the VM layer’s life cycle is consistent with that of the V layer. Even if the data comes in, the VM layer can send data by sensing the host’s life cycle without causing a memory leak. And there are no references to layer V.

  • Data sharing between fragments can be achieved. For example, activities in the home page usually have four tabs, all of which are fragments. If the Fragment needs to be delivered, it is inevitable to write some callback or hold a reference of another Fragment, which is highly coupled. Now you can use the same ViewModel for all four fragments

  • I can’t think of anything else. If you do, let me know in the comments section