玩转android.arch之lifecycle

上一篇讲到了android.arch中的room库,作为sqlite的上层封装是相当不错的。

引言

anroid.arch库中有一个lifecycle的库跟踪android中activity,fragment,service的生命周期,以免发生内存泄露。
在平常开发中我们会经常用到异步线程,无论是使用原生的asynctask,loader,原始的thread+handler 或者用流行的异步库rxjava,作异步操作,都很有容易忽略在activity退出时,异步线程可能仍然还在运行,这样很容易造成内部线程对象引用了外部的activity最终导致activity无法被回收。

有经验的同学可能会记得在activity的onpause,onstop或ondestory时退出线程。解决activity生命周期问题目前也有相当成熟的库如Rxlifecycle,这个库可以直接和rxjava配合使用以解决rxjava中线程的退出问题。但android.arch中的lifecycle库可以做得很多。

入门

先看Api

** Interfaces

LifecycleObserver Marks a class as a LifecycleObserver.
LifecycleOwner A class that has an Android lifecycle.
LifecycleRegistryOwner Specialization of LifecycleOwner that explicitly returns LifecycleRegistry.

** Class

Lifecycle Defines an object that has an Android Lifecycle.
LifecycleActivity Activity that implements LifecycleOwner.
LifecycleFragment A fragment that is also a LifecycleOwner.
LifecycleRegistry An implementation of Lifecycle that can handle multiple observers.
LifecycleService A Service that is also a LifecycleOwner.

就四个接口和五个类。
* lifecycle定义了组件生命周期事件和状态。
* LifecycleRegistryOwner 继承了Lifecycle,维护整个lifecycle.
* LifecycleActivity,LifecycleFragment,LifecycleService实现LifecycleOwner接口,提供组件的LifecycleRegistryOwner(lifecycle).
* LifecycleRegistryOwner提供addObserver()将生命周期暴露给observer.

dependences(module的build.gradle)

dependencies {
    implementation "android.arch.lifecycle:runtime:1.0.0-alpha5"
    implementation "android.arch.lifecycle:extensions:1.0.0-alpha5"
    annotationProcessor "android.arch.lifecycle:compiler:1.0.0-alpha5"
}

上代码

使用rxjava,以mvp为模式

ComponentLifecycle.java (和rxjava结合,将事件通过rxjava发出去,差不多就是自己实现了个rxlifecycle)

public class ComponentLifecycle implements LifecycleObserver {
    private String TAG = "LifecycleObserver";
    Lifecycle.Event event;
    Lifecycle lifecycle;
    BehaviorSubject<Lifecycle.Event> lifeCycleSubject;

    public void setLifCycle(@NonNull Lifecycle lifecycle, @NonNull Lifecycle.Event event){
        this.lifecycle = lifecycle;
        lifecycle.addObserver(this);
        this.event = event;
        lifeCycleSubject = BehaviorSubject.create();
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    void onCreate(){
        if(event == Lifecycle.Event.ON_CREATE){
            onEvent(event);
        }
        Log.i(TAG, "ON_CREATE: ");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    void onStart(){
        if(event == Lifecycle.Event.ON_START){
            onEvent(event);
        }
        Log.i(TAG, "onStart: ");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    void onResume(){
        if(event == Lifecycle.Event.ON_RESUME){
            onEvent(event);
        }
        Log.i(TAG, "onResume: ");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    void onPause(){
        if(event == Lifecycle.Event.ON_PAUSE){
            onEvent(event);
        }
        Log.i(TAG, "onPause: ");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    void onStop(){
        if(event == Lifecycle.Event.ON_STOP){
            onEvent(event);
        }
        Log.i(TAG, "onStop: ");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    void onDestroy(){
        if(event == Lifecycle.Event.ON_DESTROY){
            onEvent(event);
        }
        lifecycle.removeObserver(this);
        Log.i(TAG, "onDestroy: ");
    }

  public void onEvent(Lifecycle.Event event){
      lifeCycleSubject.onNext(event);
      lifeCycleSubject.onComplete();
      Log.i(TAG, "onEvent: " );
  }
}

MainPresenter.java

public class MainPresenter extends ComponentLifecycle{
    public static final String TAG = "MainPresenter";
    public  <T>ObservableTransformer<T,T>  bindUntilLifeCycle(){
            return upstream -> upstream.takeUntil(lifeCycleSubject);
    }

    protected <T> ObservableTransformer<T, T> applyAsync() {
        return observable -> observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilLifeCycle());
    }

    void requestData(){
        Observable.interval(1, TimeUnit.SECONDS).compose(applyAsync()).subscribe( res -> Log.i(TAG, "requestData: " + res));
    }

}

MainActivity.java

public class MainActivity extends LifeCycleActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MainPresenter presenter = new MainPresenter();
        presenter.setLifCycle(getLifecycle(), Lifecycle.Event.ON_DESTROY);
        presenter.requestData();

    }
}

08-04 11:30:23.225 4904-4904/app.base I/LifecycleObserver: ON_CREATE:
08-04 11:30:23.229 4904-4904/app.base I/LifecycleObserver: onStart:
08-04 11:30:23.234 4904-4904/app.base I/LifecycleObserver: onResume:
08-04 11:30:24.227 4904-4904/app.base I/MainPresenter: requestData: 0
08-04 11:30:25.227 4904-4904/app.base I/MainPresenter: requestData: 1
08-04 11:30:26.226 4904-4904/app.base I/MainPresenter: requestData: 2
08-04 11:30:27.228 4904-4904/app.base I/MainPresenter: requestData: 3
08-04 11:30:28.228 4904-4904/app.base I/MainPresenter: requestData: 4
08-04 11:30:29.228 4904-4904/app.base I/MainPresenter: requestData: 5
08-04 11:30:30.227 4904-4904/app.base I/MainPresenter: requestData: 6
08-04 11:30:30.706 4904-4904/app.base I/LifecycleObserver: onPause:
08-04 11:30:31.077 4904-4904/app.base I/LifecycleObserver: onStop:
08-04 11:30:31.078 4904-4904/app.base I/LifecycleObserver: onEvent:
08-04 11:30:31.078 4904-4904/app.base I/LifecycleObserver: onDestroy:

destroy后rxjava线程就自动退出 。

最后

LifecycleActivity继承自FragmentActivity,很多时候我们需要使用AppcompatActivity来使用appbar来使用作一些特效,继承AppcompatActivity同样参照LifeCycleActivity 实现lifecycleOwner即可。

Note: Since the Architecture Components are in alpha stage, Fragment and AppCompatActivity classes cannot implement it (because we cannot add a dependency from a stable component to an unstable API). Until Lifecycle is stable, LifecycleActivity and LifecycleFragment classes are provided for convenience. After the Lifecycles project is released, support library fragments and activities will implement the LifecycleOwner interface; LifecycleActivity and LifecycleFragment will be deprecated at that time. Also, see Implementing LifecycleOwner in custom activities and fragments.

google说了android.arc库目前是alpha阶段,等稳定后会让support包中的fragment要和activities都实现lifecycle owner. 根据release notes,现在已经到alpha9,快了。

发表评论

电子邮件地址不会被公开。 必填项已用*标注