publicinterfaceLifecycleOwner{ /** * Returns the Lifecycle of the provider. * * @return The lifecycle of the provider. */ @NonNull Lifecycle getLifecycle(); }
使用 support 包时,AppCompatActivity 就是一个 LifecycleOwner。具体的实现是 SupportActivity:
publicstaticvoidinjectIfNeededIn(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(); } }
@Override publicvoidonDestroy(){ super.onDestroy(); dispatch(Lifecycle.Event.ON_DESTROY); // just want to be sure that we won't leak reference to an activity mProcessListener = null; }
publicenum Event { /** * Constant for onCreate event of the {@link LifecycleOwner}. */ ON_CREATE, /** * Constant for onStart event of the {@link LifecycleOwner}. */ ON_START, /** * Constant for onResume event of the {@link LifecycleOwner}. */ ON_RESUME, /** * Constant for onPause event of the {@link LifecycleOwner}. */ ON_PAUSE, /** * Constant for onStop event of the {@link LifecycleOwner}. */ ON_STOP, /** * Constant for onDestroy event of the {@link LifecycleOwner}. */ ON_DESTROY, /** * An {@link Event Event} constant that can be used to match all events. */ ON_ANY }
/** * Lifecycle states. You can consider the states as the nodes in a graph and * {@link Event}s as the edges between these nodes. */ publicenum State { /** * Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch * any more events. For instance, for an {@link android.app.Activity}, this state is reached * <b>right before</b> Activity's {@link android.app.Activity#onDestroy() onDestroy} call. */ DESTROYED,
/** * Initialized state for a LifecycleOwner. For an {@link android.app.Activity}, this is * the state when it is constructed but has not received * {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} yet. */ INITIALIZED,
/** * Created state for a LifecycleOwner. For an {@link android.app.Activity}, this state * is reached in two cases: * <ul> * <li>after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call; * <li><b>right before</b> {@link android.app.Activity#onStop() onStop} call. * </ul> */ CREATED,
/** * Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state * is reached in two cases: * <ul> * <li>after {@link android.app.Activity#onStart() onStart} call; * <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call. * </ul> */ STARTED,
/** * Resumed state for a LifecycleOwner. For an {@link android.app.Activity}, this state * is reached after {@link android.app.Activity#onResume() onResume} is called. */ RESUMED;
/** * Compares if this State is greater or equal to the given {@code state}. * * @param state State to compare with * @return true if this State is greater or equal to the given {@code state} */ publicbooleanisAtLeast(@NonNull State state){ return compareTo(state) >= 0; } } }
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; } thrownew IllegalArgumentException("Unexpected event value " + event); }
privatestatic Event downEvent(State state){ switch (state) { case INITIALIZED: thrownew IllegalArgumentException(); case CREATED: return ON_DESTROY; case STARTED: return ON_STOP; case RESUMED: return ON_PAUSE; case DESTROYED: thrownew IllegalArgumentException(); } thrownew IllegalArgumentException("Unexpected state value " + state); }
privatestatic Event upEvent(State state){ switch (state) { case INITIALIZED: case DESTROYED: return ON_CREATE; case CREATED: return ON_START; case STARTED: return ON_RESUME; case RESUMED: thrownew IllegalArgumentException(); } thrownew IllegalArgumentException("Unexpected state value " + state); } }
/** * Custom list that keeps observers and can handle removals / additions during traversal. * * 这个 Invariant 非常重要,他会影响到 sync() 的逻辑 * Invariant: at any moment of time for observer1 & observer2: * if addition_order(observer1) < addition_order(observer2), then * state(observer1) >= state(observer2), */ private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap = new FastSafeIterableMap<>();
// happens only on the top of stack (never in reentrance), // so it doesn't have to take in account parents privatevoidsync(){ LifecycleOwner lifecycleOwner = mLifecycleOwner.get(); if (lifecycleOwner == null) { Log.w(LOG_TAG, "LifecycleOwner is garbage collected, you shouldn't try dispatch " + "new events from it."); return; } while (!isSynced()) { // mNewEventOccurred 是为了在 observer 触发状态变化时让 backwardPass/forwardPass() // 提前返回用的。我们刚准备调他们,这里设置为 false 即可。 mNewEventOccurred = false; // no need to check eldest for nullability, because isSynced does it for us. if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) { // mObserverMap 里的元素的状态是非递增排列的,也就是说,队头的 state 最大 // 如果 mState 小于队列里最大的那个,说明有元素需要更新状态 // 为了维持 mObserverMap 的 Invariant,这里我们需要从队尾往前更新元素的状态 backwardPass(lifecycleOwner); } Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest(); // 如果 mNewEventOccurred,说明在上面调用 backwardPass() 时,客户触发了状态修改 if (!mNewEventOccurred && newest != null && mState.compareTo(newest.getValue().mState) > 0) { forwardPass(lifecycleOwner); } } mNewEventOccurred = false; }
// 如果所有的 observer 的状态都已经同步完,则返回 true privatebooleanisSynced(){ if (mObserverMap.size() == 0) { returntrue; } State eldestObserverState = mObserverMap.eldest().getValue().mState; State newestObserverState = mObserverMap.newest().getValue().mState; // 因为我们保证队头的 state >= 后面的元素的 state,所以只要判断头尾就够了 return eldestObserverState == newestObserverState && mState == newestObserverState; }
在看这两个方法时,可以参考上面的状态图。比方说,假设当前队列里的元素都处于 CREATED。接着收到了一个 ON_START 事件,从图里面可以看出,接下来应该是要到 STARTED 状态。由于 STARTED 大于 CREATED,所以会执行 forwardPass()。forwardPass() 里面调用 upEvent(observer.mState),返回从 CREATED 往上到 STARTED 需要发送的事件,也就是 ON_START,于是 ON_START 事件发送给了客户。
// 这段注释应该是这整个类里面最难理解的了吧,至少对于我来说是这样 // we have to keep it for cases: // void onStart() { // // removeObserver(this),说明 this 是一个 LifecycleObserver // // 所以这里说的是,我们在回调里执行了下面两个操作 // mRegistry.removeObserver(this); // mRegistry.add(newObserver); // } // 假定现在我们要从 CREATED 转到 STARTED 状态(也就是说,mState 现在是 STARTED)。 // 这种情况下,只有将新的 observer 设置为 CREATED 状态,它的 onStart 才会被调用 // 为了得到这个 CREATED,在这里才引入了 mParentStates。在 forwardPass 中执行 // pushParentState(observer.mState) 时,observer.mState 就是我们需要的 CREATED。 // backwardPass 的情况类似。 // newObserver should be brought only to CREATED state during the execution of // this onStart method. our invariant with mObserverMap doesn't help, because parent observer // is no longer in the map. private ArrayList<State> mParentStates = new ArrayList<>();
private State calculateTargetState(LifecycleObserver observer){ Entry<LifecycleObserver, ObserverWithState> previous = mObserverMap.ceil(observer);
State siblingState = previous != null ? previous.getValue().mState : null; State parentState = !mParentStates.isEmpty() ? mParentStates.get(mParentStates.size() - 1) : null; // 返回最小的 state return min(min(mState, siblingState), parentState); }
publicclassLifecycleRegistryextendsLifecycle{ @Override publicvoidremoveObserver(@NonNull LifecycleObserver observer){ // we consciously decided not to send destruction events here in opposition to addObserver. // Our reasons for that: // 1. These events haven't yet happened at all. In contrast to events in addObservers, that // actually occurred but earlier. // 2. There are cases when removeObserver happens as a consequence of some kind of fatal // event. If removeObserver method sends destruction events, then a clean up routine becomes // more cumbersome. More specific example of that is: your LifecycleObserver listens for // a web connection, in the usual routine in OnStop method you report to a server that a // session has just ended and you close the connection. Now let's assume now that you // lost an internet and as a result you removed this observer. If you get destruction // events in removeObserver, you should have a special case in your onStop method that // checks if your web connection died and you shouldn't try to report anything to a server. mObserverMap.remove(observer); } }