当前位置: 首页 > news >正文

jetpack之lifecycle的原理分析

我们之前知道了lifecycle的奇妙之处,那么lifecycle为什么会如此奇妙?💭

前置知识

没有看过lifecyce基础的可以看这篇文章:

jetpack之lifecycle的入门使用[特殊字符]https://blog.csdn.net/i_xiang_la_shi/article/details/147167228了解过上面的文章,我们就能够知道lifecycle中有几个类:LifecycleOwnerLifecycleObserver

核心组件

其实这两个类就是lifecycle的两个核心组件,除了这两个,还有一个我们在使用的时候看不到的大能:LifecycleRegistry。

所以,构成lifecyc的核心组件有:LifecycleOwner、LifecycleObserver以及LifecycleRegistry。

LifecycleOwner——生命周期持有者

我们先看看熟悉的lifecycleowner的源码吧:

public interface LifecycleOwner {
    /**
     * Returns the Lifecycle of the provider.
     *
     * @return The lifecycle of the provider.
     */
    public val lifecycle: Lifecycle
}

上面的代码很简单,lifecycowner的接口的内容也很少,就只有一个lifecycle的对象。

实现了LifecycleOwner的类都是具有生命周期的例如AppcompatActivity以及Fragment。

在此就拿Fragment的源码做说明:

在如上的图片中我们可以看到Fragment实现了LifecycleOwner。这样,我们就能够为Fragment组件来添加观察者了。😋

LifecycleRegistry——生命周期的注册中心

先说一下它的作用:

  • 管理 LifecycleOwner 的生命周期状态(如 CREATEDRESUMED)。
  • 维护观察者列表,并在状态变化时通知所有注册的 LifecycleObserver

它的重要程度可见一斑,我们来分析一下它的源码:

open class LifecycleRegistry private constructor(
    provider: LifecycleOwner,
    private val enforceMainThread: Boolean
) : Lifecycle() {
//...
}

我们可以看到,它实现了抽象类Lifecycle。其实在LifecycleOwner中的Licycle实例一般都是LifecycleRegistry。

那么他是如何管理LifecycleOwner的生命周期状态的?

public enum class State {
        /**
         * Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch
         * any more events. For instance, for an [android.app.Activity], this state is reached
         * **right before** Activity's [onDestroy][android.app.Activity.onDestroy] call.
         */
        DESTROYED,

        /**
         * Initialized state for a LifecycleOwner. For an [android.app.Activity], this is
         * the state when it is constructed but has not received
         * [onCreate][android.app.Activity.onCreate] yet.
         */
        INITIALIZED,

        /**
         * Created state for a LifecycleOwner. For an [android.app.Activity], this state
         * is reached in two cases:
         *
         *  * after [onCreate][android.app.Activity.onCreate] call;
         *  * **right before** [onStop][android.app.Activity.onStop] call.
         *
         */
        CREATED,

        /**
         * Started state for a LifecycleOwner. For an [android.app.Activity], this state
         * is reached in two cases:
         *
         *  * after [onStart][android.app.Activity.onStart] call;
         *  * **right before** [onPause][android.app.Activity.onPause] call.
         *
         */
        STARTED,

        /**
         * Resumed state for a LifecycleOwner. For an [android.app.Activity], this state
         * is reached after [onResume][android.app.Activity.onResume] is called.
         */
        RESUMED;
    @MainThread
    @Deprecated("Override [currentState].")
    open fun markState(state: State) {
        enforceMainThreadIfNeeded("markState")
        currentState = state
    }

 在它的源码里面发现了markState的代码,在其中我们可以看到他有一个赋值方法,这小子藏着坏呢(〃>目<),其中的代码并不是直接将state这个状态赋值过去。

override var currentState: State
        get() = state
        /**
         * Moves the Lifecycle to the given state and dispatches necessary events to the observers.
         *
         * @param state new state
         */
        set(state) {
            enforceMainThreadIfNeeded("setCurrentState")
            moveToState(state)
        }

我们可以看到它的赋值是进入了一个moveToState方法:,这里我就只需要知道,这个方法是进行了时间分发,和state的更新即可。

如何实现第二个作用的?

override fun addObserver(observer: LifecycleObserver) {
        enforceMainThreadIfNeeded("addObserver")
        val initialState = if (state == State.DESTROYED) State.DESTROYED else State.INITIALIZED
        val statefulObserver = ObserverWithState(observer, initialState)
        val previous = observerMap.putIfAbsent(observer, statefulObserver)
        if (previous != null) {
            return
        }
        val lifecycleOwner = lifecycleOwner.get()
            ?: // it is null we should be destroyed. Fallback quickly
            return
        val isReentrance = addingObserverCounter != 0 || handlingEvent
        var targetState = calculateTargetState(observer)
        addingObserverCounter++
        while (statefulObserver.state < targetState && observerMap.contains(observer)
        ) {
            pushParentState(statefulObserver.state)
            val event = Event.upFrom(statefulObserver.state)
                ?: throw IllegalStateException("no event up from ${statefulObserver.state}")
            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()
        }
        addingObserverCounter--
    }

这个方法相信大家都不陌生了。

它的作用就是LifecycleRegistry的第二个作用了——维护观察者列表,并在状态变化时通知所有注册的 LifecycleObserver。

LifecycleRegistry先解析到这里,接下来我们看LifecycleObserver:

LifecycleObserver——生命周期观察者

它的作用是:

监听生命周期事件(如 ON_CREATEON_RESUME),通过注解或接口实现回调

因为在上面的LifecycleRegitry中我们知道了只有注册了观察者我们才能够让lifecycle感知到此组件(指的是添加了观察者的组件)的生命周期变化,这里,我就不贴源码了。😋

运作流程​

​1. 观察者注册​
  • 通过 lifecycle.addObserver() 注册观察者。
  • LifecycleRegistry 内部维护 ObserverWithState 列表,封装观察者及其当前状态。
​2. 事件分发​
  • Activity 生命周期方法(如 onCreate())被调用时,LifecycleRegistry 通过 handleLifecycleEvent() 更新状态并遍历观察者列表,调用其对应的回调方法。
  • ​线程安全​​:强制在主线程执行状态更新(enforceMainThreadIfNeeded方法),避免并发问题。
​3. 状态同步​
  • 新注册的观察者会立即收到当前状态的同步事件(如注册时 Activity 已处于 RESUMED 状态,则触发 ON_CREATEON_STARTON_RESUME 回调)。

如果觉得主包讲得好,给主包一个大大的关注吧😚。

相关文章:

  • 4.13学习总结
  • rag相关的技术
  • CSS 列表样式学习笔记
  • Spring Security 权限配置详解
  • 【5G-A学习】ISAC通信感知一体化学习小记
  • Elasticsearch搜索引擎 3(DSL)
  • 2025.4.7-2025.4.13文献阅读
  • 「Flutter」Flutter集成Google Ads广告
  • WXJ196微机小电流接地选线装置使用简单方便无需维护
  • 路由策略/策略路由之route-policy
  • 水下塑料垃圾识别分割数据集labelme格式2703张6类别
  • Redis实现签到功能
  • SSM智能排课系统
  • SpringBoot 自定义输出控制台图标
  • ANP协议深度解析:智能体网络协议的演进与革新
  • 完整源码停车场管理系统,含新能源充电系统,实现了停车+充电一体化
  • Java学习手册:Java反射与注解
  • 企业级JDK升级思路分享(一)JDK11升级到JDK17
  • UE5蓝图设置界面尺寸大小
  • 【小工具】定时任务执行器
  • 当“诈骗诱饵”盯上短剧
  • 网警打谣:传播涉刘国梁不实信息,2人被处罚
  • 体坛联播|热刺追平单赛季输球纪录,世俱杯或创收20亿美元
  • 穆迪下调美国主权信用评级
  • 沪喀同心|为新疆青少年提供科普大餐,“小小博物家(喀什版)”启动
  • 上海国际电影节纪录片单元,还世界真实色彩