Let ordinary Java classes automatically perceive Activity Lifecycle

Source: Internet
Author: User

Background

In Android development, we are familiar with the Activity's Lifecycle and will perform specific operations under a specific Lifecycle. Of course, we know that Lifecycle itself is a feature of Android, that try to imagine, what if 普通的 Java Class 也能自动感知 Lifecycle 呢 ? It doesn't seem to make much sense to listen to this idea, but in practical exploration, we find that this feature can achieve some of the optimizations that were not previously considered or difficult to achieve. Java Learning Group 669823128

This article shares the framework we developed based on this idea: AutoLifecycle and some of the interesting practices it brings.

    • Optimization One: Automatically cancels network request return when activity enters OnDestroy
    • Optimization Two: Automatically advance the network request time before the view rendering, improve the page opening speed
    • Optimization Three: MVP improvement, let presenter and view automatic Bind/unbind

Note: The references mentioned below are referred to Lifecycle-Aware here 让普通 Java Class 自动获取 Lifecycle .

Practice and Optimization One: Automatically cancels network request return when activity enters OnDestroy

In the network request, I believe everyone has an experience: in each network results back, we do the first thing is not to show the data, but write a if-else judge activity is still in.

Mtopapiobservable ...  . Subscribe (new subscriber<object> () {      @Override      void OnNext (Object data) {        //Show Data} ...});     

Because network requests are asynchronous, you have to make such judgments to prevent unpredictable null pointer problems or memory leaks.

Since you are always worried about Activity being absent, then if we pass Lifecycle-Aware让每个网络请求能自动感知Activity的onDestroy事件 ,

And at the onDestroy time, automatically put the network request results 取消掉不再返回 , that will be able to eliminate this worry.

Mtopapiobservable ...  //Bind activity's OnDestroy event  . Subscribe (new subscriber<object> () {      @Override      void OnNext (//go directly to display data} ...});     

One of the most critical is compose(bindUntilEvent(ActivityLifecycle.DESTROY)) this sentence, the effect that it can achieve is: once it Activity happens onDestroy , Observer the data will stop Subscriber flowing inward. This ensures that there onNext is no need to worry about Activity Destroy this situation.

In the above network request practice, you can also change according to your own situation Destroy and Stop Pause so on, and you can see that this automatic cancellation mechanism can be applied to any Observable , not only the network request.

Optimization Two: Accelerate page rendering before the network request is automatically advanced to view inflate

Let's start with the principle of this optimization.

In general, we'll Activity onCreate execute the following code in turn:

@Overrideprotected void OnCreate (Bundle savedinstancestate) {    Super. OnCreate (savedinstancestate);    Setcontentview (r.layout.xxx);   //Inflate View    presenter//initiating a network request}     

That is Inflate View , before and 初始化View after the network request is initiated to load the data.

In fact, network requests do not occupy the main thread, and if you can Inflate View initiate network requests on other threads before, you can shorten the entire page display time 100ms-200ms .

Loadbeforeinflate Optimization Effect

Now with   autolifecycle   Framework, we can easily implement: Let presenter automatically listen to  , inflate View This life cycle, At that time, the network request can be initiated.

public  Class newpresenter {public newpresenter (IView IView) {... //to autolifecycle Register autolifecycle.getinstance (). Init (this) ; } //when activity inflate view is automatically callback  @AutoLifecycleEvent (activity = activitylifecycle.pre_inflate) private void onhostpreinflate () { Loaddatafromserver (); //initiating network Request} ...}            

At this point, our activity does not have to be called manually presenter.loadDataFromServer(); , as the presenter Inflate View automatically initiates a network request when the event is sensed.

@OverrideonCreate//No need to start a network request manually} 

After testing, to ensure that a single network request time-consuming, the page onCreate from 显示数据 the rendering time can be 550ms shortened to 367ms , that is, 30%-40% the optimization, the effect is very good, and the code is more concise and clear.

By simply registering AutoLifecycle , you Presenter can automatically perceive all of them Lifecycle , even including custom special Lifecycle , such as:

Lifecycleawarepresenter

Optimization Three: MVP improvement, let presenter and view automatic Bind/unbind

The first optimization comparison is straightforward, you can first make a visual impression.

Our project is based on the MVP project, for Presenter the use of a fixed code that is called at the time of invocation onCreate bindView() onDestroy unBindView() . Such as:

Publicclass oldactivity extends baseactivity {basepresenter mPresenter = Span class= "Hljs-keyword" >new basepresenter ();  @Override protected void OnCreate (@ Nullable bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Mpresenter.bindview (this); //oncreate when manual bind Presenter and IView}  @Override protected void OnDestroy () {Mpresenter.unbindview (); Span class= "hljs-comment" >//OnDestroy manual Unbindview super.ondestroy ();}}     

Well, now that we can 让一个普通类自动感知Lifecycle , it can actually make sense when it's Presenter onCreate 自动bindView perceived onDestroy 自动unBindView .

The improved code is as follows:

PublicClassNewactivityExtendsbaseactivity {Newpresenter Mpresenter;@Overrideprotected void OnCreate (@NullableBundle savedinstancestate) {Super.oncreate (savedinstancestate); Mpresenter =NewNewpresenter (this);Only need to create}}publicClassNewpresenter {Privateiview miview; public newpresenter (IView IView) {this.miview = IView; //register with Autolifecycle to get lifecycle callback autolifecycle.getinstance ( ). Init (this); //automatically calls OnCreate activitylifecycle. create) private void Onhostcreate () {BindView (Miview);} //automatically calls OnDestroy activitylifecycle. destroy) private void Onhostdestroy () {Unbindview ();}       

In fact, in the ordinary development of everyone, there will be many similar Presenter classes: 需要在某个特定的Lifecycle下执行一些动作 . At this point it is possible to Lifecycle-Aware let this ordinary class automatically execute, instead of going to each Activity/Fragment one to write it over and improve the cohesion of the class.

The core principle of autolifecycle

(TL;DR)

The following is an introduction to the AutoLifecycle key implementation section, which interested readers can refer to.

1. Allow activity to send lifecycle events externally

The used RxJava students know that there is one PublishSubject , based on the Observer mode, actively send and receive messages. Here we use PublishSubject to send the lifecycle event. See below:

The lifecycle event here can be defined by itself, such as the previously mentioned Pre_inflate event, which was sent before Setcontentview, similar to:

2. Perceiving the occurrence of a lifecycle and automatically executing callbacks

The above mentioned, PublishSubject not only can send messages, but also to accept their own messages. Based on this feature, we can listen to every lifecycleevent. Such as:

The parameter observable here is the function that we want to be called back, Icontextlifecycle is the specified lifecycle. That is, when the specified lifecycle event occurs, the provided observable is automatically subscribe.

Based on this function, it is possible to implement the annotations in scene one and scene two above @AutoLifecycleEvent , that is, the @AutoLifecycleEvent function of labeling is packaged into a observable, which can be used executeOn to register the execution life cycle of the function.

3. Monitor lifecycle and cancel network request results

In scenario three, we provide a request for the network to stop the flow Observable Transformer of traffic as it listens to a lifecycle occurrence. The Transformer core implementation of this is:

As you can see, when the specified lifecycle occurs, our network request observable stops passing the data down.

4. Support Custom lifecycle, support activity/fragment/dialogframent, etc.

It can be seen that AutoLifecycle in addition to supporting a regular life cycle, you can also support a custom special life cycle, such as before view inflate.

In addition, the above is the activity for example, but obviously the framework can be flexible expansion, not limited to activity, but also applicable to fragment, dialogframent and so on.

Summarize

Lifecycle-AwareThought is the concept that Google has put forward: the ability to give ordinary classes an automatic sense of life cycle. And this article is based on this idea, provides some concrete practice and optimization of ideas, readers can do more according to their own situation to improve and try. Java Learning Group 669823128

Let ordinary Java classes automatically perceive Activity Lifecycle

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.