在App开发中出于减少内存泄露,合理释放资源,减少内存占用等目的,我们经常要在组件的生命周期回调函数中执行相应的代码比如像这样:
class xxActivity extend Activity{ public void onStart(){ xxx.init() } public void onStop(){ xxx.stop(); } public void onDestoryt(){ xxx.clean(); } } 复制代码
能解决问题但不够优雅,耦合度太高,我们看看我们经常使用的那些优秀的框架是怎样来处理这个问题的。
使用Glide.with()一系列的重载方法,最终通过组织的图片请求就能感知组件生命周期并做出响应处理。他是怎么做到的呢?
public static RequestManager with(@NonNull Activity activity) { return getRetriever(activity).get(activity); } 复制代码
public RequestManager get(@NonNull Activity activity) { if (Util.isOnBackgroundThread()) { return get(activity.getApplicationContext()); } else { assertNotDestroyed(activity); //在Activity中获取到FragmentManager android.app.FragmentManager fm = activity.getFragmentManager(); return fragmentGet(activity, fm, /*parentHint=*/ null, isActivityVisible(activity)); } } 复制代码
通过这些方法获取或者创建Fragment
@NonNull private RequestManager supportFragmentGet( @NonNull Context context, @NonNull FragmentManager fm, @Nullable Fragment parentHint, boolean isParentVisible) { SupportRequestManagerFragment current = getSupportRequestManagerFragment(fm, parentHint, isParentVisible); RequestManager requestManager = current.getRequestManager(); if (requestManager == null) { // TODO(b/27524013): Factor out this Glide.get() call. Glide glide = Glide.get(context); requestManager = factory.build( glide, current.getGlideLifecycle(), current.getRequestManagerTreeNode(), context); current.setRequestManager(requestManager); } return requestManager; } 复制代码
... final Map<FragmentManager, SupportRequestManagerFragment> pendingSupportRequestManagerFragments = new HashMap<>(); ... @NonNull private SupportRequestManagerFragment getSupportRequestManagerFragment( @NonNull final FragmentManager fm, @Nullable Fragment parentHint, boolean isParentVisible) { //在Fragment中找ManagerFragment SupportRequestManagerFragment current = (SupportRequestManagerFragment) fm.findFragmentByTag(FRAGMENT_TAG); if (current == null) { //如果在没找到,就在存储的map中尝试获取 current = pendingSupportRequestManagerFragments.get(fm); if (current == null) { //没有就创建新的。 current = new SupportRequestManagerFragment(); current.setParentFragmentHint(parentHint); if (isParentVisible) { current.getGlideLifecycle().onStart(); } pendingSupportRequestManagerFragments.put(fm, current); //移除 handler.obtainMessage(ID_REMOVE_SUPPORT_FRAGMENT_MANAGER, fm).sendToTarget(); } } return current; } 复制代码
如注释中所言,
fm.beginTransaction().add(current, FRAGMENT_TAG).commitAllowingStateLoss(); 复制代码
这个操作是异步的!什么概念就是试想:这样的情况
public test(){ Glide.with(activity).load("xxx1").into(target1);//1 Glide.with(activity).load("xxx1").into(target2);//2 } 复制代码
代码1和代码2被调用假设当前的activity还没有RequestManagerFragemnt,必然就会执行去创建的流程,代码1执行到了 pendingSupportRequestManagerFragments.put(fm, current);异步去添加,也就是使用handler将整个添加操作包装成了Message发送到了主线程的Looper中的messageQueue中而不是立即执行会等到Looper.looper()中遍历到它然后交给他的handler去处理他。异步添加在RFM没有添加到Activity中的时候,然后代码2就执行了同样也Activity中没有RFM也会去创建,这样就会在同一Activity中有两个RequesManagerFragment就出事了,所以引入了pendingSupportRequestManagerFragments,保证不会有上述情况的发生。向Activity中添加RFM这个异步任务之后,向Handler发送移除从pendingSupportRequestManagerFragments移除,这样就保证,在添加成功之前,都能在pendingSupportRequestManagerFraments中获取到RFM。
public class SupportRequestManagerFragment extends Fragment { private final ActivityFragmentLifecycle lifecycle; private final RequestManagerTreeNode requestManagerTreeNode = ... @Nullable private SupportRequestManagerFragment rootRequestManagerFragment; @Nullable private RequestManager requestManager; ... public SupportRequestManagerFragment() { this(new ActivityFragmentLifecycle()); } ActivityFragmentLifecycle getGlideLifecycle() { return lifecycle; } ... private void addChildRequestManagerFragment(SupportRequestManagerFragment child) { childRequestManagerFragments.add(child); } private void removeChildRequestManagerFragment(SupportRequestManagerFragment child) { childRequestManagerFragments.remove(child); } ... ... @Override public void onAttach(Context context) { super.onAttach(context); registerFragmentWithRoot(getActivity()); } @Override public void onDetach() { super.onDetach(); unregisterFragmentWithRoot(); } ... 复制代码
public class RequestManager implements LifecycleListener protected final Glide glide; protected final Context context; final Lifecycle lifecycle; private final RequestTracker requestTracker; ... RequestManager(...) { ... //RequestManager将自身注册到Lifecycle中也就是RequestManagerFragment中的Lifecycle lifecycle.addListener(this); lifecycle.addListener(connectivityMonitor); } public synchronized boolean isPaused() { return requestTracker.isPaused(); } public synchronized void pauseRequests() { requestTracker.pauseRequests(); } public synchronized void pauseAllRequests() { requestTracker.pauseAllRequests(); } public synchronized void resumeRequests() { requestTracker.resumeRequests(); } //相应的生命周期函数中使用处理土拍你请求 @Override public synchronized void onStart() { resumeRequests(); targetTracker.onStart(); } @Override public synchronized void onStop() { pauseRequests(); targetTracker.onStop(); } //在onDestoty中取消解除绑定释放请求中的设计的资源 @Override public synchronized void onDestroy() { targetTracker.onDestroy(); targetTracker.clear(); requestTracker.clearRequests(); lifecycle.removeListener(this); ... glide.unregisterRequestManager(this); } } 复制代码
为一个Request拥有所在组件的感知能力需要以下步骤:
1.从给定的组件(Fragment/FragmentActivity/Activity...)获取出FragmentManager。
2.创建一个不带界面的Fragment(SupportRequestManagerFragment/RequestManagerFragment),这个不带界面的Frament有个Lifecycle成员变量,在Fragment创建的时候被初始化,用于监听此Fragment的生命周期。
3.将不带界面的Frament添加进给定组件。
4.创建RequestManager,RequestManager实现了LifecycleListener,创建的时候会传入无界面fragment中成员Lifecyle,RequestManager会把自己注册到Lifecycle中,这样RequestManager就拥有了感知组件生命周期的能力。
对RxLifecycle原理分析主要是依据trello的RxLifecycle,github传送门 点这里
在Activity中使用为例,主要是使用以下两个方法:
bindUntilEvent(@NonNull ActivityEvent event) bindToLifecycle() 复制代码
使用的姿势是这样的:当Activity 回调onDestory生命周期函数的时候,就会解除订阅。
Observable.interval(1, TimeUnit.SECONDS) .compose(bindUntilEvent(ActivityEvent.DESTROY)) .subscribe(); 复制代码
追根溯源看看 要先理解Rxjava2中compose()操作符的含义 compose操作符是在不破坏rxjava流式基础上把当前的Observable转换为另一个Observable,传入的是一个Transformer对象使用。更为详细的关于这个操作符的介绍点这
public abstract class RxActivity extends Activity implements LifecycleProvider<ActivityEvent> { private final BehaviorSubject<ActivityEvent> lifecycleSubject = BehaviorSubject.create(); @CheckResult public final <T> LifecycleTransformer<T> bindUntilEvent(@NonNull ActivityEvent event) { return RxLifecycle.bindUntilEvent(lifecycleSubject, event); } public final <T> LifecycleTransformer<T> bindToLifecycle() { return RxLifecycleAndroid.bindActivity(lifecycleSubject); } protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); lifecycleSubject.onNext(ActivityEvent.CREATE); } .... .... protected void onDestroy() { lifecycleSubject.onNext(ActivityEvent.DESTROY); super.onDestroy(); } } 复制代码
关于Transformer构建在RxlifeCycle类中主要是以下三个方法:
@CheckReturnValue public static <T, R> LifecycleTransformer<T> bindUntilEvent(@Nonnull final Observable<R> lifecycle,@Nonnull final R event) { ...判空 return bind(takeUntilEvent(lifecycle, event)); } 复制代码
使用filter()操作符,获取一个过滤出传入的指定事件,其他事件不向下游分发的Observer,也就是只发送指定事件的Observable。
private static <R> Observable<R> takeUntilEvent(final Observable<R> lifecycle, final R event) { return lifecycle.filter(new Predicate<R>() { @Override public boolean test(R lifecycleEvent) throws Exception { return lifecycleEvent.equals(event); } }); 复制代码
将上一步得到的Observable其实是一个BehaviorSubject,当做构造参数传入LifecycleTransformer
public static <T, R> LifecycleTransformer<T> bind(@Nonnull final Observable<R> lifecycle) { return new LifecycleTransformer<>(lifecycle); } 复制代码
看看LifecyclerTranformer里卖的啥药
public final class LifecycleTransformer<T> implements ObservableTransformer<T, T>, FlowableTransformer<T, T>, SingleTransformer<T, T>, MaybeTransformer<T, T>, ... @Override public ObservableSource<T> apply(Observable<T> upstream) { return upstream.takeUntil(observable); } ... } 复制代码
真相大白,对upstream也就是我们使用时,xxx.compose()时的那个Observerable进行了takeUtil()操作。 takeUtil的语义是
Returns an Observable that emits the items emitted by the source Observable until a second ObservableSource emits an item. 返回一个发送事件的观察源,直到第二个被观察者发送数据。
综上当给被观察序列compose了Transformer对象后,会在相应的生命周期函数中终止。
SupportActivity类实现了LifecycleOwner结构
public class SupportActivity extends Activity implements LifecycleOwner { private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this); protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ReportFragment.injectIfNeededIn(this); } public Lifecycle getLifecycle() { return this.mLifecycleRegistry; } 复制代码
具有感知所在组件的能力在相应的生命周期回调函数里向LifecycleRegistry分发事件。
# ReportFragment public static void injectIfNeededIn(Activity activity) { // ProcessLifecycleOwner should always correctly work and some activities may not extend // FragmentActivity from support lib, so we use framework fragments for activities android.app.FragmentManager manager = activity.getFragmentManager(); if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) { manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit(); // Hopefully, we are the first to make a transaction. manager.executePendingTransactions(); } } private void dispatch(Lifecycle.Event event) { Activity activity = getActivity(); if (activity instanceof LifecycleRegistryOwner) { ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event); return; } /**2**/ if (activity instanceof LifecycleOwner) { Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle(); if (lifecycle instanceof LifecycleRegistry) { ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event); } } } 复制代码
注释2处
先来一张官方的图
Jetpack对组件生命周期的管理有两个核心的概念事件(Event)和状态(State)。 他们直接的关系是 事件驱动状态的转换 。
一共有五种状态,五种状态之间是怎样通过事件驱动的方式实现转换的呢,如上图所示,
图看百遍其意自现,其实当我们得知某种事件之后就能准确的得知出他将进入的状态体现就是在LifecycleRegistry的getStateAfter()方法中,就不用文字描述了很代码很能说明问题。
static State getStateAfter(Event event) { switch (event) { case ON_CREATE: case ON_STOP: return CREATED; case ON_START: case ON_PAUSE: return STARTED; case ON_RESUME: return RESUMED; case ON_DESTROY: return DESTROYED; case ON_ANY: break; } throw new IllegalArgumentException("Unexpected event value " + event); } 复制代码
LifecycleRegistry实现了Lifecyle抽象类,是生命周期监听者和分发生命周期事件的实际管理和分发者。其中的方法
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) { State next = getStateAfter(event); moveToState(next); } 复制代码
根据事件能获取到组件进入的下一个状态,然后将通知监听改变状态 :moveToState(next);MoveToState()方中,修改LifecycleRegistry中mState状态,然后调用 sync()方法。
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap = new FastSafeIterableMap<>(); 复制代码
LifecycleRegistry中有mObserverMap存储这生命周期观察者,FastSafeIterableMap是一个Map的数据结构,key为LifecycleObserver,value为ObserverWithState。
static class ObserverWithState { State mState; GenericLifecycleObserver mLifecycleObserver; ObserverWithState(LifecycleObserver observer, State initialState) { mLifecycleObserver = Lifecycling.getCallback(observer); mState = initialState; } void dispatchEvent(LifecycleOwner owner, Event event) { State newState = getStateAfter(event); mState = min(mState, newState); mLifecycleObserver.onStateChanged(owner, event); mState = newState; } } 复制代码