Android builds MVVM architecture from scratch (2)————ViewModel

When I really contacted and used the MVVM architecture, the whole person was not good. Because I personally feel that MVVM is more difficult to learn than MVC and MVP, and the knowledge of design is not a little bit. So I want to slowly record my growth. Hope to correct if there is any mistake.

Build MVVM architecture from scratch series articles (continuous update):
Android build MVVM architecture from scratch (1)————DataBinding
Android build MVVM architecture from scratch (2)————ViewModel
Android build MVVM architecture from scratch (3)————LiveData
Android build MVVM architecture from scratch (4)————Room (from entry to advanced)
Android build MVVM architecture from scratch (5)————Lifecycles
Android build from scratch MVVM architecture (6) ———— Use the Play Android API to take you to build the MVVM framework (Elementary)
Android builds the MVVM architecture from scratch (7) ———— Use the Play Android API to take you to build the MVVM framework (The ultimate article)

Still that picture AAC (Android Architecture Components)

In this article, we talk about ViewModel. Here we just briefly understand the ViewModel in MVVM. After we understand these components, we will use wanAndroid api to review the topic MVVM project.


One, ViewModel

Remember the Model in MVP. The ViewModel here is somewhat similar to the role of the Model in MVP. But google released a set of AAC components. These components allow developers to develop efficient projects. The ViewModel is also one of the components.

1.1. Why is there this ViewModel component

Description : ViewModel is a way to store and manage the lifecycle of data related UI
role :
1, in the MVVM pattern, the separation of Model and View
2, ui responsible for preparing the data
3, data storage

The biggest highlight here is the life cycle approach. Example: If used in Activity. He will run through the life cycle of the entire Activity. Look at the picture first:

First summarize the results as follows (use examples to verify later):

  • The ViewModel will only survive in the Activity and will only be created once. When it is destroyed, onClered will be called actively.

Why is the whole life cycle approach important? For example: apps need to frequently request data asynchronously, such as requesting network tuning interfaces, which are quite time-consuming. For example, the interface request returns only after the Activity is destroyed. Considering the memory leak, it will add a lot of complicated work to us. But now we can solve this problem by using ViewModel to handle data callbacks. It means that as long as we inherit our ViewModel, any bugs that may appear, Google will help us deal with it.

  • Because it is only created once when the Activity is alive, then all Fragments under this Activity can share a ViewModel
  • Since the life cycle of the ViewModel may be longer than the life cycle of the activity, in order to avoid memory leaks, Google prohibits holding a reference to the Context or activity or view in the ViewModel. If you have to use Context,
    you can inherit the ApplicationContext from the AndroidViewModel class
  • Previously, when we destroyed and rebuilt the activity, we could use the activity's onSaveInstanceState() mechanism to save and restore data, but the shortcomings were obvious, and it was
    only suitable for saving a small amount of data that could be serialized and deserialized. If we need to save a relatively large data, this time ViewModel can be achieved.


How do you look at the above life cycle diagram?

1. Activity created (3 life cycles have gone), which corresponds to the scope of the ViewModel.

2. Activity rorared (similar to switching the horizontal and vertical screens), still corresponds to scope

3. Finish( ) (Activity destruction), the dependency is scope

4, Finished (has been destroyed). Call onCleared of ViewModel.

It's vague to say that, look at an example


Two, explore the life cycle of ViewModel

We first create our MyViewModel, inheriting ViewModel. And rewrite onCleared()

public class MyViewModel extends ViewModel {
    
    
    @Override
    protected void onCleared() {
    
    
        super.onCleared();
        LogUtils.i("MyViewModel的相关","Activity被杀死后也会被销毁!");
    }
}

Click on the source code of ViewModel:


Because this layer does not reveal the specific implementation of specific life cycle binding and destruction. We have to find the implementation class. Here we are based on the principle of simple use, then I will directly print the hashCode value of MyViewModel in the Activity to verify the above figure, the code in the Activity. Let me talk about it here, here we use the ViewModelProciders class, so we need to introduce the next dependency

implementation ‘android.arch.lifecycle:extensions:1.1.1’

public class ViewModelActivity extends FragmentActivity {
    
    

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_viewmodel);
        MyViewModel myViewModel = ViewModelProviders.of(this).get(MyViewModel.class);
        LogUtils.i("MyViewModel的相关", "onCreate ==> " + myViewModel.hashCode());
    }

    @Override
    protected void onStart() {
    
    
        super.onStart();
        MyViewModel myViewModel = ViewModelProviders.of(this).get(MyViewModel.class);
        LogUtils.i("MyViewModel的相关", "onStart ==> " + myViewModel.hashCode());
    }

    @Override
    protected void onResume() {
    
    
        super.onResume();
        MyViewModel myViewModel = ViewModelProviders.of(this).get(MyViewModel.class);
        LogUtils.i("MyViewModel的相关", "onResume ==> " + myViewModel.hashCode());
    }

    @Override
    protected void onPause() {
    
    
        super.onPause();
        MyViewModel myViewModel = ViewModelProviders.of(this).get(MyViewModel.class);
        LogUtils.i("MyViewModel的相关", "onPause ==> " + myViewModel.hashCode());
    }

    @Override
    protected void onStop() {
    
    
        super.onStop();
        MyViewModel myViewModel = ViewModelProviders.of(this).get(MyViewModel.class);
        LogUtils.i("MyViewModel的相关", "onStop ==> " + myViewModel.hashCode());
    }


    @Override
    protected void onDestroy() {
    
    
        super.onDestroy();
        MyViewModel myViewModel = ViewModelProviders.of(this).get(MyViewModel.class);
        LogUtils.i("MyViewModel的相关", "onDestroy ==> " + myViewModel.hashCode());
    }
}

After running the project, look at the print; here you can see that the hashCode values ​​are all the same. :

Then we let the phone switch horizontally and vertically to see the print. You can also see that the hashCode value is the same, unchanged:

Finally, we exit this page and watch the print. Here, the hashCode value is recreated after the onCleared of the ViewModel is called and destroyed. The only suspicious point here is that this is somewhat different from the official website map. The destruction of ViewModel is onClered, which is the previous step of Ondestroy (just different from the graphic effect, but the process is correct. If you are familiar with this piece, please give pointers):


3. Sharing data with Fragment

For example, there are many Fragments displayed in our Activity. We only need to look at the code in a fragment here to make it clear

//从getActivity()这句,那可不是同一个MyViewModel吗。
ViewModelProviders.of(getActivity()).get(MyViewModel.class)

So far, a simple introduction and use of the simple ViewModel have been made. Let us slowly implement our own MVVM framework together! !

This article's demo address

Guess you like

Origin blog.csdn.net/leol_2/article/details/102396064