joy keeps flowin'

Jetpack系列之Lifecycle

xx
目次

Android中又越来越多组件依赖Lifecycle,从来不好奇Lifecycle是什么东西,又是怎么起作用的吗?我很好奇。

LifecycleOwner #

通常的用法往往是从LifecyclerOwner中拿到Lifecycle对象,之后add Oberver或者remove Observer。

LifecycleOwner是一个接口,只有一个参数(说是方法更确切):Lifecycle。单纯的为了拿到Lifecycle对象。

FragmentActivity和Fragment都继承自LifecycleOwner。内部又都持有一个LifecycleRegistry对象。

我在想为什么需要这么一个方法呢? 如果没有这个方法会怎么呢?如果没有,每个持有Lifecycle的类中都需要保存Lifecycle,这是少不了的。获取就不一样了,怎么获取呢?每个类没有统一的方法啊。这么想LifecycleOwner就是统一的方法。对外只暴露拿到Lifecycle的方法。

Lifecycle #

LifecycleRegistry是Lifecycle对应的唯一实现,内部实现了记录Observer数量、添加、移除和改变状态的实际逻辑,不一一列举。

Lifecycle是个抽象类,方法有两个:addObserver和removeObserver。参数都是一个LifecycleObserver示例。也不太需要解释,就是添加和移除Observer。

此外还有一个State类型成员变量(可以理解成返回State类型的方法),保存当前的状态。

State #

 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
/**
 * Lifecycle states. You can consider the states as the nodes in a graph and
 * [Event]s as the edges between these nodes.
 */
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;

    /**
     * Compares if this State is greater or equal to the given `state`.
     *
     * @param state State to compare with
     * @return true if this State is greater or equal to the given `state`
     */
    public fun isAtLeast(state: State): Boolean {
        return compareTo(state) >= 0
    }
}

LifecycleObserver #

LifecycleObserver是一个接口(废话),单纯的是一个接口。

1
2
3
4
5
6
7
8
/**
 * Marks a class as a LifecycleObserver. Don't use this interface directly. Instead implement either
 * [DefaultLifecycleObserver] or [LifecycleEventObserver] to be notified about
 * lifecycle events.
 *
 * @see Lifecycle Lifecycle - for samples and usage patterns.
 */
public interface LifecycleObserver

代码就是这么定义的。

对应的实现接口有两个:LifecycleEventObserver和DefaultLifecycleObserver。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
/**
 * Class that can receive any lifecycle change and dispatch it to the receiver.
 *
 * If a class implements both this interface and
 * [androidx.lifecycle.DefaultLifecycleObserver], then
 * methods of `DefaultLifecycleObserver` will be called first, and then followed by the call
 * of [LifecycleEventObserver.onStateChanged]
 *
 * If a class implements this interface and in the same time uses [OnLifecycleEvent], then
 * annotations will be ignored.
 */
public fun interface LifecycleEventObserver : LifecycleObserver {
    /**
     * Called when a state transition event happens.
     *
     * @param source The source of the event
     * @param event The event
     */
    public fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event)
}
 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
public interface DefaultLifecycleObserver : LifecycleObserver {
    /**
     * Notifies that `ON_CREATE` event occurred.
     *
     *
     * This method will be called after the [LifecycleOwner]'s `onCreate`
     * method returns.
     *
     * @param owner the component, whose state was changed
     */
    public fun onCreate(owner: LifecycleOwner) {}

    /**
     * Notifies that `ON_START` event occurred.
     *
     *
     * This method will be called after the [LifecycleOwner]'s `onStart` method returns.
     *
     * @param owner the component, whose state was changed
     */
    public fun onStart(owner: LifecycleOwner) {}

    /**
     * Notifies that `ON_RESUME` event occurred.
     *
     *
     * This method will be called after the [LifecycleOwner]'s `onResume`
     * method returns.
     *
     * @param owner the component, whose state was changed
     */
    public fun onResume(owner: LifecycleOwner) {}

    /**
     * Notifies that `ON_PAUSE` event occurred.
     *
     *
     * This method will be called before the [LifecycleOwner]'s `onPause` method
     * is called.
     *
     * @param owner the component, whose state was changed
     */
    public fun onPause(owner: LifecycleOwner) {}

    /**
     * Notifies that `ON_STOP` event occurred.
     *
     *
     * This method will be called before the [LifecycleOwner]'s `onStop` method
     * is called.
     *
     * @param owner the component, whose state was changed
     */
    public fun onStop(owner: LifecycleOwner) {}

    /**
     * Notifies that `ON_DESTROY` event occurred.
     *
     *
     * This method will be called before the [LifecycleOwner]'s `onDestroy` method
     * is called.
     *
     * @param owner the component, whose state was changed
     */
    public fun onDestroy(owner: LifecycleOwner) {}
}

两者的差别在提供的颗粒度不一样,一个是把每一个状态都提供了方法;另一个则是只提供了变化的callback,至于怎么用完全不关心。

先后顺序 #

接口LifecycleEventObserver的注释中表明如果同时实现两个接口,会先调用DefaultLifecycleObserver中的方法,然后再调用LifecycleEventObserver的方法。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
internal class DefaultLifecycleObserverAdapter(
    private val defaultLifecycleObserver: DefaultLifecycleObserver,
    private val lifecycleEventObserver: LifecycleEventObserver?
) : LifecycleEventObserver {
    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        when (event) {
            Lifecycle.Event.ON_CREATE -> defaultLifecycleObserver.onCreate(source)
            Lifecycle.Event.ON_START -> defaultLifecycleObserver.onStart(source)
            Lifecycle.Event.ON_RESUME -> defaultLifecycleObserver.onResume(source)
            Lifecycle.Event.ON_PAUSE -> defaultLifecycleObserver.onPause(source)
            Lifecycle.Event.ON_STOP -> defaultLifecycleObserver.onStop(source)
            Lifecycle.Event.ON_DESTROY -> defaultLifecycleObserver.onDestroy(source)
            Lifecycle.Event.ON_ANY ->
                throw IllegalArgumentException("ON_ANY must not been send by anybody")
        }
        lifecycleEventObserver?.onStateChanged(source, event)
    }
}

规则和顺序很清晰,又是怎么从Observer到DefaultLifecycleObserverAdapter的呢?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// Lifecycling.kt
public fun lifecycleEventObserver(`object`: Any): LifecycleEventObserver {
  val isLifecycleEventObserver = `object` is LifecycleEventObserver
  val isDefaultLifecycleObserver = `object` is DefaultLifecycleObserver
  if (isLifecycleEventObserver && isDefaultLifecycleObserver) {
    return DefaultLifecycleObserverAdapter(
      `object` as DefaultLifecycleObserver,
    `object` as LifecycleEventObserver
  )
  }
  ...

方法lifecycleEventObserver会在LifecycleRegistry添加Observer时被调用,所有的也都串起来了。

总结 #

注:实线表示持有,虚线表示继承

来个图
标签:
Categories: