In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to use ViewModel". In daily operation, I believe many people have doubts about how to use ViewModel. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use ViewModel". Next, please follow the editor to study!
1 main functions
Data storage during the survival period of Activity and Fragment
Data sharing among multiple Fragment of the same Activity in bind
Code decoupling independently or in cooperation with LiveData
2 method of use
1) introduce ViewModel
Add a compiled lifecycle.extensions module to the build.gradle, which contains both ViewModel and LiveData:
Compile ('android.arch.lifecycle:extensions:1.0.0')
Since lifecycle.extensions internally relies on the 26.1.0 version of the support_ v7 package, it is recommended that the referenced support_v7 component version in the project be upgraded to 26.1.0 or above.
2) construct data objects
Custom ViewModel class, inheriting ViewModel
Add the required data objects to the custom ViewModel class
Public class DemoViewModel extends ViewModel {final public DemoData mData = new DemoData (); public DemoViewModel () {}}
3) get data
Get ViewModelProvider through ViewModelProviders and Activity / Fragment
Get custom ViewModel objects through ViewModelProvider and custom ViewModel classes
Get the data object from the custom ViewModel object and do the necessary read and write operations.
DemoData data = ViewModelProviders.of (getActivity ()) .get (DemoViewModel.class) .mData; data.doSth (); 3 usage scenario demonstration 1) data maintenance between single Activity and multiple Fragment
Point of demand:
Bind Fragment An and B of the same Activity
There is a jump relationship between Fragment An and B
Fragment An and B work together to maintain some data, and both An and B have business requirements for reading and modifying.
Traditional implementation method 1:Intent + onFragmentResult ()
General process:
When you jump, you need to package the data into the Bundle by pressing KMurv, or pass the data Parcelable to the next page.
After the next page modifies the data and returns, you need to parse and synchronize the data from the Intent of onFragmentResult ()
The total data size transmitted by Intent cannot exceed 1m.
Troublesome and limited in size.
Traditional implementation method 2: data object SingleInstance, static
Disadvantages:
The life cycle of data should be controlled by itself.
Prone to memory leaks
It is equally troublesome and risky.
ViewModel also avoids the shortcomings of traditional methods:
Bind Fragments of the same Activity can obtain common data objects through ViewModelProvider, without the need for active data transmission
Get rid of the troublesome controls such as Intent, Bundle and Parcelable.
Data lifecycle is controlled internally by ViewModel without manual management of destruction
2) cooperate with LiveData to realize UI and business logic layering
LiveData, which is also an official architecture component, is used to listen for data changes and call back to the registered observer. ViewModel+LiveData can easily abstract the data layer and business layer and decouple quickly.
The following Demo is from an official case. From the fact that Demo, LiveData and ViewModel are in the same module, we can see that officials highly recommend the use of both. Combined with the previous Data-Binding, we can quickly build a set of simple MVVM business system.
Public class MyViewModel extends ViewModel {private MutableLiveData users; public LiveData getUsers () {if (users= = null) {users= new MutableLiveData (); loadUsers ();} return users;} private void loadUsers () {/ / Do an asyncronous operation to fetch users. }} public class MyActivity extends AppCompatActivity {public void onCreate (Bundle savedInstanceState) {/ / Create a ViewModel the first time the system calls an activity's onCreate () method. / / Re-created activities receive the same MyViewModel instance created by thefirst activity. MyViewModel model = ViewModelProviders.of (this) .get (MyViewModel.class); model.getUsers () .observe (this,users-> {/ / update UI});}} 4 Lifecycle Features
The life cycle of ViewModel is synchronized with Lifecycle, and when Activity / Fragment is out of range of Lifecycle (not an onDestroy () callback), ViewModel is destroyed along with the data it contains. How big is it, according to the official statement:
In the case of an activity, when it finishes, whilein the case of a fragment, when it's detached.
After Activity unstacks (Fragment removes the relationship with Activity), ViewModel is dereferenced and ready to be reclaimed by the system.
5 source code analysis
Simply do the following source code analysis with two minor problems:
1) how is the mapping relationship between ViewModel and Activity / Fragment established? (take Activity as an example)
Part one: get ViewModelProvider
Call ViewModelProviders.of (Activity)
Call all the way to HolderFragmentManager.holderFragmentFor (Activity)
HolderFragmentManager looks in turn from the HashMap held by FragmentManager and HolderFragmentManager: whether the Activity is mapped by HolderFragment (the role of HolderFragment will be discussed in the next question)
HolderFragment.class HolderFragment holderFragmentFor (FragmentActivity activity) {FragmentManagerfm = activity.getSupportFragmentManager (); HolderFragment holder = findHolderFragment (fm); if (holder! = null) {return holder;} else {holder = (HolderFragment) this.mNotCommittedActivityHolders.get (activity); if (holder! = null) {return holder;} else {/ / create HolderFragment
If the HolderFragment; is returned, create a HolderFragment if not:
Create a new HolderFragment,commit for FragmentManager and store it in HashMap to mark it as not committed status to prevent duplicate commit
Register with Application to monitor the life cycle of the Activity. If the HolderFragment has been destroyed before create,Activity, remove the Activity from the HashMap to prevent leakage
After the HolderFragment is successfully created, remove the Activity from the HashMap
Use the ViewModelStore object held by HolderFragment to create the ViewModelProvider
The first part is responsible for building / looking up the HolderFragment, protecting against exceptions during the build, and finally returning the ViewModelProvider. ViewModelStore, jointly held by HolderFragment and ViewModelProvider, will be the core of the second part.
(part II: get ViewModel)
Call ViewModelProvider.get (ViewModel.class)
Use the specification name (canonical name) of the ViewModel to find out if an instance of the ViewModel already exists in the HashMap. Return if there is one; if not, build one through reflection and store it in HashMap
ViewModelStore.class public class ViewModelStore {private final HashMap mMap = new HashMap ()
The second part is responsible for mapping, looking up ViewModel instances from HashMap by class name. The whole mapping logic can also be simplified to find the ViewModel instance through the Activity class name.
2) how to manage the life cycle of ViewModel?
ViewModel objects are scoped to the Lifecycle passed to the ViewModelProvider when getting the ViewModel.
Seeing this sentence in the official document, I wonder if ViewModel manages its life cycle through Lifecycle, which is also an official architectural component.
In fact, it's not that complicated. ViewModel is created by calling ViewModelProvider.get (ViewModel.class) for the first time, while destruction depends on HolderFragment's own onDestroy () callback:
HolderFragment.class public void onDestroy () {super.onDestroy (); this.mViewModelStore.clear ();} ViewModelStore.class public final void clear () {Iteratorvar1 = this.mMap.values (). Iterator (); while (var1.hasNext ()) {ViewModel vm = (ViewModel) var1.next (); vm.onCleared ();} this.mMap.clear ();}
After the HolderFragment is destroyed, call ViewModelStore.clear () to clean up the reference of the HashMap to the ViewModel object and wait for the system GC to recycle the ViewModel. This also explains why HolderFragment is needed to create ViewModelProvider, and HolderFragment controls the lifecycle of ViewModel.
6 Last but not least
Briefly describe the main responsibilities of the components of the official structure:
Lifecycle: throws Activity / Fragment lifecycle callback events outward
LiveData: listening for changes in data within the scope of Lifecycle
ViewModel: storing and sharing data within Lifecycle
Room: simplify Db operation
In addition to Room, you can feel that the authorities are trying to guide everyone from the original MVC to MVVM, and the more powerful official components will make the UI- business-data abstraction process easier and smoother.
At this point, the study on "how to use ViewModel" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.