Android builds MVVM architecture from scratch (5)————Lifecycles

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 Lifecycles . After we understand and recognize Lifecycles, we will finally apply it to our MVVM project. This article is my own summary, if there are any errors, please correct me


1. Introduction and brief understanding of Lifecycles

Introduction : The
role of components that can perceive the life cycle : monitor the life cycle components such as Activity/Fragment and notify other components in time when the life cycle changes

Including LifecycleOwner, LifecycleObserver. We can understand it this way. LifecycleOwner is the observer. We can look at the source code (Returns the Lifecycle of the provider, so long can be considered to be observed), and LifecycleObserver can be the observer.

Think about it, if we don’t have a LiveData component, but we still need to implement it: when the life cycle of the Activity is onStart and onResume, LiveData will be in the active state, and the updated data will be notified to the corresponding Activity
. If the life cycle is onStop or onPause, The data update is not called back until the life cycle is onResume, the callback is immediately called back. Without LiveData, we have to write a bunch of judgments in the code and in the Activity to realize this function, and now Lifecycles has helped us realize this function, we just use it. Let's take a look at the LiveData we talked about before, the code for LiveData to monitor changes:

@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        //this这里的类型就是LifecycleOwner,
        liveData.observe(this, new Observer<String>() {
    
    
            //这里就就是一旦被观察者LifecycleOwner的生命周期改变,就会通知观察者liveData调用onChanged。
            @Override
            public void onChanged(String s) {
    
    
                
            }
        });
    }

Why can this be used directly here? I also explained it before. In the Support library after version 26, LifecycleOwner is implemented in AppCompatActivity and SupportActivity, and the life cycle of the UI interface has been processed internally. We can enter the code directly, as follows

If it’s not clear here, let’s implement LifecycleOwner and LifecycleObserver ourselves (you need to know the components of Google, which are already handled for us internally)


2. Realize LifecycleOwner by yourself (the life cycle of the observer)

  • We create an Actvity, inherit the Activity class, and note that LifecycleOwner is not implemented.
  • Implement LifecycleOwner yourself and provide the life cycle of the observed
  • new a LiveData, and realize LiveData data change monitoring.
  • When onstop, post data to LiveData

Activity is as follows:

public class LifecyclesActivity extends Activity implements LifecycleOwner {
    
    
    private MutableLiveData<String> liveData = new MutableLiveData<>();
    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
    
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lifecycles);
        liveData.observe(this, new Observer<String>() {
    
    
            @Override
            public void onChanged(String s) {
    
    
                LogUtils.i("观察LiveData", " ==> " + s);
            }
        });

    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
    
    
        mLifecycleRegistry.markState(Lifecycle.State.CREATED);
        super.onSaveInstanceState(outState);
    }

    @NonNull
    @Override
    public Lifecycle getLifecycle() {
    
    
        return mLifecycleRegistry;
    }

    @Override
    protected void onStop() {
    
    
        super.onStop();
        liveData.postValue("运行试试");
    }
}

After running to see the print, press the home button to exit, and then click back. The same effect of our previous LiveData also appeared: it will not print when leaving the interface, and print immediately when returning to the interface.


Third, implement LifecycleObserver (observer) by yourself

We create a new MyObserver ourselves to monitor all life cycles

public class MyObserver implements LifecycleObserver {
    
    
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void onCreate() {
    
    
        LogUtils.i("MyObserver","onCreate");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onStart() {
    
    
        LogUtils.i("MyObserver","onStart");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void onResume() {
    
    
        LogUtils.i("MyObserver","onResume");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void onPause() {
    
    
        LogUtils.i("MyObserver","onPause");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onStop() {
    
    
        LogUtils.i("MyObserver","onStop");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void onDestory() {
    
    
        LogUtils.i("MyObserver","onDestory");
    }

//    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
//    public void onAny() {
    
    
//        LogUtils.i("MyObserver","onAny");
//    }
}

Then in Activtiy, add

@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
    
    

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lifecycles);
        getLifecycle().addObserver(new MyObserver());

    }

After running, look at the print, I will not post the effect here . When we use Lifecycles in the project, we don't need to consider the above. I'm just here to tell you briefly what lifecycles mean. Google has encapsulated everything we need to deal with in these components.

So far we have a general understanding of lifecycles. Come on

This article's demo address

Guess you like

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