Android Official architecture Components introduction of ViewModel (iii)

Source: Internet
Author: User

ViewModel

Application components such as activity,fragment have their own lifecycle and are managed by the Android framework. The framework may destroy and refactor activity or fragment based on the user's actions and the state of the device. As developers, we cannot intervene in these actions.

So some of the data in activity or fragment is lost as it is destroyed and rebuilt with refactoring. For example, there is a list of users in your activity, and when the activity is refactored, the new activity will retrieve the user list again. For some simple data, the activity can use the onSaveInstanceState() method and retrieve it from the OnCreate bundle. However, this approach is only suitable for some simple UI states, which is not suitable for a large number of user lists.

There is also a problem where activity or fragment often do some asynchronous time-consuming operations. It is then necessary for activity and fragment to manage these asynchronous operations and to clean them up when they are destroyed, thus ensuring that the memory overflow problem occurs. This kind of processing will become very complex as the project expands, and your app will be crash if you're not careful.

Activity and fragment itself need to handle the input events of many users and deal with the operating system, so when they take time to manage their data resources, the class file becomes unusually large, and then it creates the so-called god activities and god fragments . These UI control classes can handle all related transactions by just one class. It's nothing like God. But these classes are awkward if they are to be unit tested.

So there's MVC MVP this kind of design pattern that separates the view from the data. The same is true of the ViewModel class today, which is about separating the data from the UI. And when activity or fragment is refactored, ViewModel automatically retains the previous data and uses it for new activity or fragment. For an example of the list of users mentioned above, ViewModel will manage this data well for us.

 Public classMyviewmodelextendsViewModel {PrivateMutablelivedata<list<user>>users;  PublicLivedata<list<user>>getusers () {if(Users = =NULL) {Users=NewMutablelivedata<list<users>>();        Loadusers (); }        returnusers; }    Private voidloadusers () {//Do async operation to fetch users    }}

And then we can use it in our activity:

 Public class extends appcompatactivity {    publicvoid  onCreate (Bundle savedinstancestate) {        = Viewmodelproviders.of (this). Get (Myviewmodel.  Class);        Model.getusers (). Observe (This, users, {            //  update UI         });    }}

This is when myactivity is reconstructed, the model instance obtained is the same as the one before refactoring, and when MyActivity is destroyed, the framework calls ViewModel onCleared() , and we can do the cleanup of resources in this method.

Because the life cycle of ViewModel is separate from activity or fragment, it is absolutely not possible to refer to any view object or any object referencing the activity's context in ViewModel. If you need application context in ViewModel, you can inherit it AndroidViewModel .

Data sharing between fragment

It is very common to wrap multiple fragment in the activity and need to communicate with each other, then you need these fragment to define some interfaces and then let the activity coordinate. And these fragment also need to deal with other fragment that are not visible or have not yet created these detail issues.

The above move point can be easily solved by ViewModel, imagine intention has such activity, it contains Fragmenta and FRAGMENTB, where a is the user list, B is the user's detailed data, click on the list of a user, in B display the corresponding data.

See how to deal with this problem with ViewModel:

 Public classSharedviewmodelextendsViewModel {Private FinalMutablelivedata<item> selected =NewMutablelivedata<item>();  Public voidSelect (item item) {Selected.setvalue (item); }     PublicLivedata<item>getselected () {returnselected; }} Public classMasterfragmentextendsFragment {PrivateSharedviewmodel model;  Public voidonactivitycreated () {model= Viewmodelproviders.of (Getactivity ()). Get (Sharedviewmodel.class); Itemselector.setonclicklistener (Item-{model.select (item);    }); }} Public classDetailfragmentextendslifecyclefragment { Public voidonactivitycreated () {Sharedviewmodel model= Viewmodelproviders.of (Getactivity ()). Get (Sharedviewmodel.class); Model.getselected (). Observe ( This, {item--//Update UI        }); }}

It is important to note that two fragment are used getActivity as parameters to obtain the ViewModel instance. This means that the ViewModel objects obtained by these two fragment are the same.

The benefits of using the ViewModel are as follows:

    • The activity does not need to do anything and does not interfere with the communication between the two fragment.
    • Fragment do not need to know each other, even if one disappears invisible, the other can work very well.
    • Fragment have their own life cycle, they do not interfere with each other, even if you use a FRAGMENTC instead of B,fragmenta can work normally, there is no problem.
The life cycle of ViewModel

The life cycle of the ViewModel is then passed along ViewModelProvider LifeCycle , and when an instance of ViewModel is generated, it stays in memory until the corresponding lifecycle is completely closed. The following is a diagram of the life cycle of the ViewModel with activity:

Transfer from https://www.cnblogs.com/zqlxtt/p/6888507.html

Android Official architecture Components introduction of ViewModel (iii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.