首页 抽丝剥茧 Jetpack | Lifecycle 源码解析
文章
取消

抽丝剥茧 Jetpack | Lifecycle 源码解析

如果你对裹脚布般的源码分析不感兴趣,可以阅读上一篇文章 抽丝剥茧 Jetpack | Lifecycle 到底解决了什么问题? ,用伪代码的形式构造了 Jetpack Lifecycle 的基本架构,搭配本文食用更佳。

在分析源码之前,还是必须得回顾一下 Event 和 State 关系,这是理解整个 Lifecycle 的基础。

State 和 Event

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public abstract class Lifecycle {
	public enum Event {
        ON_CREATE,
        ON_START,
        ON_RESUME,
        ON_PAUSE,
        ON_STOP,
        ON_DESTROY,
        ON_ANY; 
  }
  
  public enum State {
        DESTROYED,
        INITIALIZED,
        CREATED,
        STARTED,
        RESUMED;
  }
  
  ...
}

七个生命周期事件,五种生命周期状态。不用死记硬背,对着我画的这张图仔细想一下。

重点看两个东西。第一,生命周期状态的值的大小。第二,生命周期事件带来的生命周期状态的流转 。理解这两个之后,我们再直插源码,深入理解 Lifecycle 的实现原理。

庖丁解牛 Lifecycle

Lifecycle 的实现其实很简单,简单到就两步:

  • 生命周期组件 LifecycleOwner 在特定的生命周期时机,分发对应的生命周期事件 Event 给到 生命周期观察者 LifecycleObserver
  • LifecycleObserver 处理相应的 Event 并回调对应方法,执行特定逻辑。

那我们就从 LifecycleOwner 生命周期事件的分发开始。

直接看 ComponentActivity.onCreat() 方法。

1
2
3
4
5
6
7
8
9
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
     		...
        // 看这里
        ReportFragment.injectIfNeededIn(this);
        if (mContentLayoutId != 0) {
            setContentView(mContentLayoutId);
        }
    }

ReportFragment.injectIfNeededIn(this) 很容易让你想到通过空 Fragment 来代理生命周期,其实并不完全是。

1
2
3
4
5
6
7
8
9
10
11
12
    public static void injectIfNeededIn(Activity activity) {
        if (Build.VERSION.SDK_INT >= 29) {
			  // >= 29,直接使用 Activity.registerActivityLifecycleCallbacks
            LifecycleCallbacks.registerIn(activity);
        }
      	// 小于 29,使用 ReportFragment 转发
        android.app.FragmentManager manager = activity.getFragmentManager();
        if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
            manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
            manager.executePendingTransactions();
        }
    }

从 API 29 开始,使用 Activity.registerActivityLifecycleCallbacks() 方法监听生命周期。之前为什么不用呢?当然因为这个方法是 29 新增的。

但无论是使用 ReportFragment 转发:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
      	// 看这里
        dispatch(Lifecycle.Event.ON_CREATE);
    }

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

    @Override
    public void onResume() {
        super.onResume();
        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);
    }

还是使用 Activity.registerActivityLifecycleCallbacks()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
    static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {

        static void registerIn(Activity activity) {
            activity.registerActivityLifecycleCallbacks(new LifecycleCallbacks());
        }

        @Override
        public void onActivityCreated(@NonNull Activity activity,
                @Nullable Bundle bundle) {
        }

        @Override
        public void onActivityPostCreated(@NonNull Activity activity,
                @Nullable Bundle savedInstanceState) {
          	// 看这里
            dispatch(activity, Lifecycle.Event.ON_CREATE);
        }

        @Override
        public void onActivityStarted(@NonNull Activity activity) {
        }

        @Override
        public void onActivityPostStarted(@NonNull Activity activity) {
            dispatch(activity, Lifecycle.Event.ON_START);
        }

        @Override
        public void onActivityResumed(@NonNull Activity activity) {
        }

        @Override
        public void onActivityPostResumed(@NonNull Activity activity) {
            dispatch(activity, Lifecycle.Event.ON_RESUME);
        }

        @Override
        public void onActivityPrePaused(@NonNull Activity activity) {
            dispatch(activity, Lifecycle.Event.ON_PAUSE);
        }

        @Override
        public void onActivityPaused(@NonNull Activity activity) {
        }

        @Override
        public void onActivityPreStopped(@NonNull Activity activity) {
            dispatch(activity, Lifecycle.Event.ON_STOP);
        }

        @Override
        public void onActivityStopped(@NonNull Activity activity) {
        }

        @Override
        public void onActivitySaveInstanceState(@NonNull Activity activity,
                @NonNull Bundle bundle) {
        }

        @Override
        public void onActivityPreDestroyed(@NonNull Activity activity) {
            dispatch(activity, Lifecycle.Event.ON_DESTROY);
        }

        @Override
        public void onActivityDestroyed(@NonNull Activity activity) {
        }
    }

最终调用的都是 dispatch() 方法。

ActivityLifecycleCallbacks 中做了更加细致的分发。onActivityPostCreated()Activity.onCreate() 之后回调,onActivityPrePaused()Activity.onPaused() 之前被回调。总结一下,

ON_CREATE、ON_START、ON_RESUME 在对应生命周期方法回调之后分发。

ON_PAUSE、ON_STOP、ON_DESTROY 在对应生命周期方法回调之前分发。

接着看分发生命周期事件的 dispatch() 方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
        if (activity instanceof LifecycleRegistryOwner) { // 已废弃
            ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
            return;
        }
				// 看这里
        if (activity instanceof LifecycleOwner) {
            Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
            if (lifecycle instanceof LifecycleRegistry) {
                // 处理生命周期事件
                ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
            }
        }
    }

这里出现了 LifecycleOwnerLifecycleRegistry

LifecycleOwner 是一个空接口,表示具备提供 Lifecycle 对象的能力。

1
2
3
4
public interface LifecycleOwner {
    @NonNull
    Lifecycle getLifecycle();
}

ComponentActivity 实现了 LifecycleOwner 接口,并返回了 mLifecycleRegistry 对象。

1
2
3
4
5
6
7
8
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
        ContextAware,
        LifecycleOwner,... {
          
		public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }          
}

ComponentActivity 作为生命周期宿主,并没有亲力亲为的处理相关逻辑,而是交给了接口 Lifecycle 的实现类 LifecycleRegistry

LifecycleRegistry 实现了 Lifecycle 的核心逻辑:处理宿主生命周期事件同步观察者状态添加/移除观察者

先来看 LifecycleRegister 类的几个主要属性。

1
2
3
4
5
6
7
8
9
10
// 可以在遍历过程中添加/移除观察者
// 如果 observer1 早于 observer2 添加,那么 observer1 的 state 不小于 observer2
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
            new FastSafeIterableMap<>();

// LifecycleOwner 当前生命周期状态
private State mState;

// 弱引用持有 LifecycleOwner,防止内存泄露
private final WeakReference<LifecycleOwner> mLifecycleOwner;

重点关注 mObserverMap ,它保存了 LifecycleObserver 和 ObserverWithState 的映射关系。记住它的一个基本原则,后添加的观察者的状态必须不大于之前添加的观察者的状态。

ObserverWithState 包装了当前生命周期状态 State 和一个生命周期事件的观察者 LifecycleEventObserver

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    static class ObserverWithState {
        State mState;
        LifecycleEventObserver mLifecycleObserver;

        ObserverWithState(LifecycleObserver observer, State initialState) {
            mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
            mState = initialState;
        }

        void dispatchEvent(LifecycleOwner owner, Event event) {
            State newState = event.getTargetState();
            mState = min(mState, newState);
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }
    }

public interface LifecycleEventObserver extends LifecycleObserver {
    void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}

之前说到,Activity 的生命周期事件通过 ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event) 分发到了 LifecycleRegistry 来处理。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        enforceMainThreadIfNeeded("handleLifecycleEvent");
      	// 看这里
        moveToState(event.getTargetState());
    }

    private void moveToState(State next) {
        if (mState == next) {
            return;
        }
        mState = next;
        if (mHandlingEvent || mAddingObserverCounter != 0) {
            mNewEventOccurred = true;
            return;
        }
        mHandlingEvent = true;
        // 看这里
        sync();
        mHandlingEvent = false;
    }

重点在 sync() 函数。分三步看。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    private void sync() {
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
      	...
        // 1. 判断状态是否同步完成
        while (!isSynced()) {
            mNewEventOccurred = false;
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                // 2. 需要下山
                backwardPass(lifecycleOwner);
            }
            Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                // 2. 需要上山
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }

首先判断是否同步完成,即 mObserverMap 中的所有观察者是否都已经同步到正确的生命周期状态。

1
2
3
4
5
6
7
8
9
10
    private boolean isSynced() {
        if (mObserverMap.size() == 0) {
            return true;
        }
      	// 最老,也就是队首的状态
        State eldestObserverState = mObserverMap.eldest().getValue().mState;
      	// 最新,也就是队尾的状态
        State newestObserverState = mObserverMap.newest().getValue().mState;
        return eldestObserverState == newestObserverState && mState == newestObserverState;
    }

mObserverMap 的基本原则:后添加的观察者的状态必须不大于之前添加的观察者的状态。 所以判断同步完成有两个条件:

  1. mObserverMap 中队首和队尾的观察者状态一致
  2. 当前生命周期状态 mState 等于 mObserverMap 队尾最新的状态

如果当前状态 mState 比 mObserverMap 最老(队首) 的状态要小,说明可能存在观察者需要同步自己的状态到更低的状态,我把它叫做 “下山”,可以对比下图中从最高点的 RESUMED 往右变小。

反之,如果当前状态 mState 比 mObserverMap 最小(队首)的状态要大,说明可能存在观察者需要同步自己的状态到更高的状态,可以看作是 “上山”

这里以 下山 为例,不再赘述上山过程。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
    private void backwardPass(LifecycleOwner lifecycleOwner) {
        // 所有观察者按降序排列
        Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
                mObserverMap.descendingIterator();
        while (descendingIterator.hasNext() && !mNewEventOccurred) {
            Map.Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
            ObserverWithState observer = entry.getValue();
            // 如果当前观察者的状态仍大于 mState ,需要继续下山
            while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) {
                // 查询下降到此状态需要发送到事件
                Event event = Event.downFrom(observer.mState);
                if (event == null) {
                    throw new IllegalStateException("no event down from " + observer.mState);
                }
                pushParentState(event.getTargetState());
                // 向订阅者分发事件
                observer.dispatchEvent(lifecycleOwner, event);
                popParentState();
            }
        }
    }

Event.downFrom() 到作用是查询下山到此状态需要发送到事件。

1
2
3
4
5
6
7
8
9
10
11
12
13
        @Nullable
        public static Event downFrom(@NonNull State state) {
            switch (state) {
                case CREATED:
                    return ON_DESTROY;
                case STARTED:
                    return ON_STOP;
                case RESUMED:
                    return ON_PAUSE;
                default:
                    return null;
            }
        }

这个不用死记硬背,再次对照这张图,一目了然。

最后通过 observer.dispatchEvent(lifecycleOwner, event) 把生命周期事件交到了订阅者手里。注意,这里的 observer 并不是 LifecycleObserver,而是 mObserverMap 中的 ObserverWithState。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    static class ObserverWithState {
        State mState;
        LifecycleEventObserver mLifecycleObserver;

        ObserverWithState(LifecycleObserver observer, State initialState) {
          	// 初始化 mLifecycleObserver
            mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
            mState = initialState;
        }

        void dispatchEvent(LifecycleOwner owner, Event event) {
            State newState = event.getTargetState();
            mState = min(mState, newState);
            // 向观察者通知生命周期状态变化
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }
    }

重点在于 mLifecycleObserver 。看一下它是如何通过 Lifecycling.lifecycleEventObserver(observer) 初始化的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
    static LifecycleEventObserver lifecycleEventObserver(Object object) {
        boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
        boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;
        // 既是 LifecycleEventObserver 又是 FullLifecycleObserver
      	// 为什么会有这种情况?
        if (isLifecycleEventObserver && isFullLifecycleObserver) {
            return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
                    (LifecycleEventObserver) object);
        }
      	// 仅实现了 FullLifecycleObserver
        if (isFullLifecycleObserver) {
            return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
        }
				// 仅实现了 LifecycleEventObserver
        if (isLifecycleEventObserver) {
            return (LifecycleEventObserver) 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);
    }

向 LifecycleObserver 通知生命周期变化有三个方案,第一个是直接走接口回调,第二个是利用注解生成代码,第三个是反射调用。后两种不建议使用,这里也不再介绍了,可以自己跟进去看一下。

继续看接口回调的方案,源码中出现了两种选择,LifecycleEventObserverFullLifecycleObserver

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public interface LifecycleEventObserver extends LifecycleObserver {
    void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}

interface FullLifecycleObserver extends LifecycleObserver {

    void onCreate(LifecycleOwner owner);

    void onStart(LifecycleOwner owner);

    void onResume(LifecycleOwner owner);

    void onPause(LifecycleOwner owner);

    void onStop(LifecycleOwner owner);

    void onDestroy(LifecycleOwner owner);
}

如果是 LifecycleEventObserver,直接回调其 onStateChanged() 方法。

如果是 FullLifecycleObserver,会包装为 FullLifecycleObserverAdapter 进行处理。实际使用中,一般不直接使用 FullLifecycleObserver ,而是使用 DefaultLifecycleObserver,利用 Java8 新增的默认接口实现简化了使用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public interface DefaultLifecycleObserver extends FullLifecycleObserver {

    @Override
    default void onCreate(@NonNull LifecycleOwner owner) {
    }

    @Override
    default void onStart(@NonNull LifecycleOwner owner) {
    }

    @Override
    default void onResume(@NonNull LifecycleOwner owner) {
    }

    @Override
    default void onPause(@NonNull LifecycleOwner owner) {
    }

    @Override
    default void onStop(@NonNull LifecycleOwner owner) {
    }

    @Override
    default void onDestroy(@NonNull LifecycleOwner owner) {
    }
}

继续看 FullLifecycleObserverAdapter 。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class FullLifecycleObserverAdapter implements LifecycleEventObserver {

    private final FullLifecycleObserver mFullLifecycleObserver;
    private final LifecycleEventObserver mLifecycleEventObserver;
		// 包装了 FullLifecycleObserver 和 LifecycleEventObserver
    FullLifecycleObserverAdapter(FullLifecycleObserver fullLifecycleObserver,
            LifecycleEventObserver lifecycleEventObserver) {
        mFullLifecycleObserver = fullLifecycleObserver;
        mLifecycleEventObserver = lifecycleEventObserver;
    }

    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
        switch (event) {
            case ON_CREATE:
                mFullLifecycleObserver.onCreate(source);
                break;
            case ON_START:
                mFullLifecycleObserver.onStart(source);
                break;
            case ON_RESUME:
                mFullLifecycleObserver.onResume(source);
                break;
            case ON_PAUSE:
                mFullLifecycleObserver.onPause(source);
                break;
            case ON_STOP:
                mFullLifecycleObserver.onStop(source);
                break;
            case ON_DESTROY:
                mFullLifecycleObserver.onDestroy(source);
                break;
            case ON_ANY:
                throw new IllegalArgumentException("ON_ANY must not been send by anybody");
        }
        if (mLifecycleEventObserver != null) {
            mLifecycleEventObserver.onStateChanged(source, event);
        }
    }
}

FullLifecycleObserver,根据 Event 调用对应的接口方法。

LifecycleEventObserver, 直接回调 onStateChanged() 方法。

注意构造函数中可以同时传入 FullLifecycleObserver 和 LifecycleEventObserver ,并且都会被通知生命周期变化,也就意味着你可以在自己的观察者中同时实现这两个接口,FullLifecycleObserver 会早于 LifecycleEventObserver 收到回调,但 LifecycleEventObserver 可以拿到具体的 Event ,FullLifecycleObserver 不行。但我暂时没想到具体的使用场景。

生命周期事件和状态的整个流转过程就结束了,最后来看一下如何添加观察者。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
    @Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        enforceMainThreadIfNeeded("addObserver");
      	// 设置初始状态
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        ...
        State targetState = calculateTargetState(observer);
        mAddingObserverCounter++;
      	// 判断是否需要上山
        while ((statefulObserver.mState.compareTo(targetState) < 0
                && mObserverMap.contains(observer))) {
            pushParentState(statefulObserver.mState);
            final Event event = Event.upFrom(statefulObserver.mState);
            if (event == null) {
                throw new IllegalStateException("no event up from " + statefulObserver.mState);
            }
          	// 处理生命周期事件
            statefulObserver.dispatchEvent(lifecycleOwner, event);
            popParentState();
            // mState / subling may have been changed recalculate
            targetState = calculateTargetState(observer);
        }

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

上面的代码省略了一些边界情况的处理。添加观察者,本质上也是一个 “上山” 的过程。生命组件当前状态不是 DESTROYED 的话,就设置观察者初始状态为 INITIALIZED ,然后逐步同步到正确的当前生命周期。要注意的是,上山过程中,每同步到一个新状态,观察者都会接收到对应的生命周期事件回调。举个例子,在 onResume 方法中调用 addObserver(observerA) ,那么 observerA 会依次收到 onCreate,onStart,onResume 回调。

最后

Lifecycle 的源码其实很简单,但它是我们理解 Jetpack 其他组件的核心重点,强烈建议由面及里,透彻理解。

系列文章

抽丝剥茧 Jetpack | Lifecycle 到底解决了什么问题?

本文由作者按照 CC BY 4.0 进行授权
热门标签
文章内容

抽丝剥茧 Jetpack | Lifecycle 到底解决了什么问题?

-

热门标签