When it comes to actually touching and using the MVVM architecture, the whole person is no good. Because personally, COMPARED with MVC and MVP, MVVM is more difficult to learn, and the knowledge of design is not the slightest bit. So I want to slowly record my growth. Please correct any mistakes.


Building an MVVM Architecture from Scratch series of articles (continuing updates) : Android builds MVVM from scratch (1) ————DataBinding Android builds MVVM from scratch (2) ————ViewModel Android builds MVVM from scratch (3) ————LiveData Android builds MVVM architecture from scratch (4) ————Room (from beginner to advanced) Android builds MVVM architecture from scratch (5) ————Lifecycles Android builds MVVM architecture from scratch (6) ———— Uses Android to play ———— Use the Android API to take you to build the MVVM framework (final)


AAC(Android Architecture Components)

In this article we’re going to talk about the ViewModel. Here we are just looking at the ViewModel in MVVM. Once these components are understood, we will go through the MVVM project using the wanAndroid API.


A, the ViewModel

Remember Model in MVP. The ViewModel here is somewhat similar to the Model in MVP. But Google came up with a suite of AAC components. These components allow developers to develop efficient projects. The ViewModel is one of the components.

1.1. Why is there a ViewModel component

ViewModel stores and manages UI-related data in a life-cycle manner: 1. In MVVM mode, separates Model from View; 2

The biggest highlight here is the lifecycle approach. Example: If used in an Activity. It runs through the entire Activity lifecycle. Here’s a picture:

Firstly, the results are summarized as follows (verified by examples later) :

  • The ViewModel will only live for the Activity and will only be created once. OnClered is actively called when it is destroyed.

Why is the whole lifecycle approach important? For example, the app needs to request data asynchronously frequently, such as requesting the network tuning interface, which is quite time consuming. For example, the interface request is returned after the Activity is destroyed, which can add a lot of complexity to our work considering memory leaks. But now we can solve this problem by using the ViewModel to handle data callbacks. As long as we inherit our ViewModel, there may be a bug, Google help us deal with.

  • Because an Activity is created only once while it is alive, all fragments under that Activity can share a ViewModel
  • Because the ViewModel life cycle can be as long as the Activity life cycle, Google disallows holding references to Context or activity or View in the ViewModel to avoid memory leaks. If you must use the Context, you can inherit the AndroidViewModel class to get the ApplicationContext
  • The onSaveInstanceState () mechanism of the activity can be used to save and restore data when the activity is destroyed and rebuilt. However, it has obvious disadvantages. It is only suitable for saving a small amount of data that can be serialized or deserialized. If we need to save a large amount of data, the ViewModel will do it.

Activity created(3 life cycles), corresponding to the scope of the ViewModel. 2, Activity rorared(similar to the screen switch), or corresponding to Scope 3, Finish () (Activity destruction), depending on scope 4, Finished (Finished). Call the onCleared ViewModel.

It’s kind of vague, but let’s do an example


Explore the ViewModel lifecycle

So let’s first create our MyViewModel, inherit the ViewModel. Rewrite the onCleared ()

public class MyViewModel extends ViewModel {
    @Override
    protected void onCleared(a) {
        super.onCleared();
        LogUtils.i("Relevance of MyViewModel"."Activities are destroyed when they are killed!"); }}Copy the code

Open ViewModel source code:

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("Relevance of MyViewModel"."onCreate ==> " + myViewModel.hashCode());
    }

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

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

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

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


    @Override
    protected void onDestroy(a) {
        super.onDestroy();
        MyViewModel myViewModel = ViewModelProviders.of(this).get(MyViewModel.class);
        LogUtils.i("Relevance of MyViewModel"."onDestroy ==> "+ myViewModel.hashCode()); }}Copy the code

After running the project, look at printing; As you can see, the hashCode values are the same. :

Then we asked the phone to switch horizontal and vertical to see the print. You can also see that the hashCode value is the same, unchanged:

Finally, we exit the page and look at printing. Here the hashCode value is recreated after the onCleared destruction of the ViewModel is called. The only difference here is that the ViewModel onClered is destroyed before Ondestroy:


3. Share data with fragments

For example, our Activity also displays many fragments. We just need to look at a Fragment of code here

// From getActivity(), that's the same MyViewModel.
ViewModelProviders.of(getActivity()).get(MyViewModel.class)
Copy the code

So far, this is a brief introduction to the simple ViewModel and its use. Let’s slowly implement our own MVVM framework!!

Demo address