LifeCycle源碼解讀

對於LifeCycle的簡單使用可以看上一篇文章:LiveData+ViewModel+Repository搭建MVVM

這篇文章主要是爲了閱讀源碼,儘量深入閱讀,能力還是一般,見諒:

LifeCycle的作用

解決onCreate等生命週期方法,由於各種原因,後期越來越臃腫的問題。

關鍵類闡述

LifecycleRegistryOwner/LifecycleOwner

在Activity等組件生命週期發生變化的時候,發出相應的Event給LifecycleRegistry。

LifecycleRegistry

控制state的轉換、接受分發Event事件。

LifecycleObserver

通過註解綁定Event和自定義的函數,實現對生命週期的監聽並處理。

Event

@SuppressWarnings("WeakerAccess")
public enum 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
}

源碼分析

依賴庫版本:implementation "android.arch.lifecycle:extensions:1.1.1"

項目地址:https://github.com/fengqingxiuyi/LiveDataDemo

入口

getLifecycle().addObserver(new ActivityLifecycleObserver(getApplicationContext()));

進入addObserver

@Override
public void addObserver(@NonNull LifecycleObserver observer) { //這裏的LifecycleObserver就是我們自定義的ActivityLifecycleObserver
    State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
    //把帶着狀態的observer封裝成ObserverWithState
    ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
    ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);

    if (previous != null) {
        return;
    }
    LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
    if (lifecycleOwner == null) {
        // it is null we should be destroyed. Fallback quickly
        return;
    }

    boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
    State targetState = calculateTargetState(observer);
    mAddingObserverCounter++;
    while ((statefulObserver.mState.compareTo(targetState) < 0
            && mObserverMap.contains(observer))) {
        pushParentState(statefulObserver.mState);
        statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
        popParentState();
        // mState / subling may have been changed recalculate
        targetState = calculateTargetState(observer);
    }

    if (!isReentrance) {
        // we do sync only on the top level.
        sync();
    }
    mAddingObserverCounter--;
}

進入ObserverWithState

static class ObserverWithState {
    State mState;
    GenericLifecycleObserver mLifecycleObserver;

    ObserverWithState(LifecycleObserver observer, State initialState) {
        //通過不同的observer返回不同的mLifecycleObserver
        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;
    }
}

進入getCallback

@NonNull
static GenericLifecycleObserver getCallback(Object object) {
    if (object instanceof FullLifecycleObserver) {
        return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
    }

    if (object instanceof GenericLifecycleObserver) {
        return (GenericLifecycleObserver) object;
    }

    final Class<?> klass = object.getClass();
    int type = getObserverConstructorType(klass);
    if (type == GENERATED_CALLBACK) {
        List<Constructor<? extends GeneratedAdapter>> constructors =
                sClassToAdapters.get(klass);
        if (constructors.size() == 1) {
            GeneratedAdapter generatedAdapter = createGeneratedAdapter(
                    constructors.get(0), object);
            return new SingleGeneratedAdapterObserver(generatedAdapter);
        }
        GeneratedAdapter[] adapters = new GeneratedAdapter[constructors.size()];
        for (int i = 0; i < constructors.size(); i++) {
            adapters[i] = createGeneratedAdapter(constructors.get(i), object);
        }
        return new CompositeGeneratedAdaptersObserver(adapters);
    }
    return new ReflectiveGenericLifecycleObserver(object); //走到了這裏
}

進入ReflectiveGenericLifecycleObserver

class ReflectiveGenericLifecycleObserver implements GenericLifecycleObserver {
    private final Object mWrapped;
    private final CallbackInfo mInfo;

    ReflectiveGenericLifecycleObserver(Object wrapped) {
        mWrapped = wrapped;
        mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
    }

    @Override
    public void onStateChanged(LifecycleOwner source, Event event) {
        mInfo.invokeCallbacks(source, event, mWrapped); //這裏:通過反射實現事件分發
    }
}

那麼是在哪裏調用onStateChanged的呢?下面我們繼續分析:

LifecycleDispatcher

When initialized, it hooks into the Activity callback of the Application and observes Activities. It is responsible to hook in child-fragments to activities and fragments to report their lifecycle events. Another responsibility of this class is to mark as stopped all lifecycle providers related to an activity as soon it is not safe to run a fragment transaction in this activity.

第一次冷啓動App的時候會通過ActivityThread創建,並且之後會在Activity創建的時候,添加ReportFragment去實現生命週期事件的分發,下面看下源碼:

@SuppressWarnings("WeakerAccess")
@VisibleForTesting
static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks {
    //省略...

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        if (activity instanceof FragmentActivity) {
            ((FragmentActivity) activity).getSupportFragmentManager()
                    .registerFragmentLifecycleCallbacks(mFragmentCallback, true);
        }
        ReportFragment.injectIfNeededIn(activity); //這裏添加了ReportFragment
    }

    //省略...
}

進入ReportFragment

@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public class ReportFragment extends Fragment {
    private static final String REPORT_FRAGMENT_TAG = "android.arch.lifecycle"
            + ".LifecycleDispatcher.report_fragment_tag";

    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();
        }
    }

    static ReportFragment get(Activity activity) {
        return (ReportFragment) activity.getFragmentManager().findFragmentByTag(
                REPORT_FRAGMENT_TAG);
    }

    private ActivityInitializationListener mProcessListener;

    private void dispatchCreate(ActivityInitializationListener listener) {
        if (listener != null) {
            listener.onCreate();
        }
    }

    private void dispatchStart(ActivityInitializationListener listener) {
        if (listener != null) {
            listener.onStart();
        }
    }

    private void dispatchResume(ActivityInitializationListener listener) {
        if (listener != null) {
            listener.onResume();
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        dispatchCreate(mProcessListener);
        dispatch(Lifecycle.Event.ON_CREATE); //這裏分發事件,我們自定義的觀察者定義的註解其實就是Lifecycle.Event.ON_CREATE這一類
    }

    @Override
    public void onStart() {
        super.onStart();
        dispatchStart(mProcessListener);
        dispatch(Lifecycle.Event.ON_START);
    }

    @Override
    public void onResume() {
        super.onResume();
        dispatchResume(mProcessListener);
        dispatch(Lifecycle.Event.ON_RESUME);
    }

    @Override
    public void onPause() {
        super.onPause();
        dispatch(Lifecycle.Event.ON_PAUSE);
    }

    @Override
    public void onStop() {
        super.onStop();
        dispatch(Lifecycle.Event.ON_STOP);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        dispatch(Lifecycle.Event.ON_DESTROY);
        // just want to be sure that we won't leak reference to an activity
        mProcessListener = null;
    }

    private void dispatch(Lifecycle.Event event) {
        Activity activity = getActivity();
        if (activity instanceof LifecycleRegistryOwner) {
            ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event); //這裏將事件分發交接給了LifecycleRegistryOwner
            return;
        }

        if (activity instanceof LifecycleOwner) {
            Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
            if (lifecycle instanceof LifecycleRegistry) {
                ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event); //這裏將事件分發交接給了LifecycleRegistry
            }
        }
    }

    void setProcessListener(ActivityInitializationListener processListener) {
        mProcessListener = processListener;
    }

    interface ActivityInitializationListener {
        void onCreate();

        void onStart();

        void onResume();
    }
}

進入handleLifecycleEvent

/**
 * Sets the current state and notifies the observers.
 * <p>
 * Note that if the {@code currentState} is the same state as the last call to this method,
 * calling this method has no effect.
 *
 * @param event The event that was received
 */
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
    State next = getStateAfter(event); //獲取下一個state
    moveToState(next);
}

這裏借用官方的一張圖(LifeCycle-States):

大概意思就是可以通過不同的Event知道不同的State。例如:當你的Event是ON_RESUME的時候就代表他當前的State是STARTED,所以Next State就是RESUMED,接着分析getStateAfter:

//對照着表其實很簡單,events是ON_CREATE和ON_STOP的下一個狀態指向都是CREATED,所以返回CREATED,其他的類似。
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);
}

所以getStateAfter獲取的是下一個State,也就是下一個生命週期。

進入moveToState

private void moveToState(State next) {
    //判斷當前State是不是等於我們上面獲取的
    if (mState == next) {
        return;
    }
    //不一樣則重新賦值
    mState = next;
    if (mHandlingEvent || mAddingObserverCounter != 0) {
        mNewEventOccurred = true;
        // we will figure out what to do on upper level.
        return;
    }
    mHandlingEvent = true;
    sync(); //同步
    mHandlingEvent = false;
}

// happens only on the top of stack (never in reentrance),
// so it doesn't have to take in account parents
private void sync() {
    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;
    }
    //當前的State和最早的State或最新的State進行比較,mObserverMap這個集合存放的是ObserverWithState,而ObserverWithState有我們的狀態。 
    while (!isSynced()) {
        mNewEventOccurred = false;
        // no need to check eldest for nullability, because isSynced does it for us.
        if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
            backwardPass(lifecycleOwner); //繼承Activity走這裏
        }
        Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
        if (!mNewEventOccurred && newest != null
                && mState.compareTo(newest.getValue().mState) > 0) {
            forwardPass(lifecycleOwner); //繼承FramgentActivity走這裏,因爲Activity的子類SupportActivity實現了LifecycleOwner,而且SupportActivity是FragmentActivity的父類
        }
    }
    mNewEventOccurred = false;
}

private void forwardPass(LifecycleOwner lifecycleOwner) {
    Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
            mObserverMap.iteratorWithAdditions();
    //第一個while循壞遍歷我們存儲觀察者的集合
    while (ascendingIterator.hasNext() && !mNewEventOccurred) {
        Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
        ObserverWithState observer = entry.getValue();
        //第二個是要處理各個狀態經過的event
        while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
                && mObserverMap.contains(entry.getKey()))) {
            pushParentState(observer.mState);
            //upEvent返回所要經歷的Event,例如:當前是STARTED, 那麼他的經過的Event就是ON_RESUME
            observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState)); //在這裏分發事件
            popParentState();
        }
    }
}

private void backwardPass(LifecycleOwner lifecycleOwner) {
    Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
            mObserverMap.descendingIterator();
    //第一個while循壞遍歷我們存儲觀察者的集合
    while (descendingIterator.hasNext() && !mNewEventOccurred) {
        Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
        ObserverWithState observer = entry.getValue();
        //第二個是要處理各個狀態經過的event
        while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
                && mObserverMap.contains(entry.getKey()))) {
            //downEvent返回下一個Event
            Event event = downEvent(observer.mState);
            pushParentState(getStateAfter(event));
            //upEvent返回所要經歷的Event,例如:當前是STARTED, 那麼他的經過的Event就是ON_RESUME
            observer.dispatchEvent(lifecycleOwner, event); //在這裏分發事件
            popParentState();
        }
    }
}

進入dispatchEvent

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;
    }
}

附上一個簡單的流程圖(圖片來源於參考文章)

參考文章

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章