Jetpack之Lifecyle原理分析

2020-05-03  本文已影响0人  有没有口罩给我一个

目录

Jetpack之Lifecyle原理分析
Jetpack之LiveData原理分析
Jetpack之ViewMdel原理分析
Jetpack之LiveData+ViewMde+Flow+Retrofit架构设计

介绍

简单使用

任何类都可以通过向其方法添加注解来监控组件的生命周期状态。然后,您可以通过调用 Lifecycle 类的 addObserver() 方法并传递观察者的实例来添加观察者,其实最终是注册到LifecycleRegistry生命周期表中

class MyObserver : LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun onResume() {}

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPauser() { }
}
myLifecycleOwner.getLifecycle().addObserver(MyObserver())

在上面的示例中,myLifecycleOwner 对象实现了 LifecycleOwner 接口,我们将在接下来的部分中对该接口进行说明。

LifecycleOwner

实现自定义 LifecycleOwner

Fragment 和 Activity 已实现 LifecycleOwner 接口。
如果我们有一个自定义类并希望使其成为 LifecycleOwner,您可以使用 LifecycleRegistry 类,但需要将事件转发到该类,比如前面说到让Dialog有用让Lifecucle感知它的生命周期,如以下代码示例中所示:。

class DialogLifeCycle(context: Context, themeResId: Int) : Dialog(context, themeResId),LifecycleOwner {
private val mDispatcher by lazy { LifecycleDispatcher(this) }
override fun getLifecycle(): Lifecycle {
    return mDispatcher.getLifecycle()
}

override fun onCreate(savedInstanceState: Bundle?) {
    mDispatcher.onDialogPreSuperOnCreate()
    super.onCreate(savedInstanceState)
}

override fun onStart() {
    mDispatcher.onDialogPreSuperOnStart()
    mDispatcher.onDialogPreSuperResume()
    super.onStart()
}

override fun onStop() {
    mDispatcher.onDialogPreSuperPause()
    mDispatcher.onDialogPreSuperOnStop()
    mDispatcher.onDialogPreSuperOnDestroy()
    super.onStop()
}

}

########LifecycleOwner帮助类

class LifecycleDispatcher(provider: LifecycleOwner) {
    private var mRegistry: LifecycleRegistry = LifecycleRegistry(provider)
    private var mHandler: Handler = Handler()
    private lateinit var mLastDispatchRunnable: DispatchRunnable

private fun postDispatchRunnable(event: Lifecycle.Event) {
    if (this::mLastDispatchRunnable.isInitialized) {
        mLastDispatchRunnable.run()
    }
    mLastDispatchRunnable = DispatchRunnable(mRegistry, event)
    mHandler.postAtFrontOfQueue(mLastDispatchRunnable)
}


fun onDialogPreSuperOnCreate() {
    postDispatchRunnable(Lifecycle.Event.ON_CREATE)
    onDialogPreSuperAny()
}


fun onDialogPreSuperOnStart() {
    postDispatchRunnable(Lifecycle.Event.ON_START)
    onDialogPreSuperAny()
}


fun onDialogPreSuperResume() {
    postDispatchRunnable(Lifecycle.Event.ON_RESUME)
    onDialogPreSuperAny()
}


fun onDialogPreSuperPause() {
    postDispatchRunnable(Lifecycle.Event.ON_PAUSE)
    onDialogPreSuperAny()
}

fun onDialogPreSuperOnDestroy() {
    postDispatchRunnable(Lifecycle.Event.ON_DESTROY)
    onDialogPreSuperAny()
}

fun onDialogPreSuperOnStop() {
    postDispatchRunnable(Lifecycle.Event.ON_STOP)
    onDialogPreSuperAny()
}

fun onDialogPreSuperAny() {
    postDispatchRunnable(Lifecycle.Event.ON_ANY)
}


fun getLifecycle(): Lifecycle {
    return mRegistry
}


class DispatchRunnable(
    private val mRegistry: LifecycleRegistry,
    private val mEvent: Lifecycle.Event,
    private var mWasExecuted: Boolean = false
) : Runnable {
    override fun run() {
        if (!mWasExecuted) {
            mRegistry.handleLifecycleEvent(mEvent)
            mWasExecuted = true
        }
    }
}

}

然后我们通过 lifecycle.addObserver(MyLifeCycle())方法将生命周期观察这注册给lifecycle,这样我们在MyLifeCycle就能感知Dialog的生命周期变化。

源码分析原理

在lifecycle.addObserver(MyLifeCycle())将生命周期观察这注册给lifecycle,那我们从这里开始:

#######MyLifeCycle

class MyLifeCycle : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate() {
    LogUtil.error("MyLifeCycle onCreate")
    }
}

我们定义的了MyLifeCycle 并让他实现LifecycleObserver ,最后编译期会生成代码,如下:

public class MyLifeCycle_LifecycleAdapter implements GeneratedAdapter {
final MyLifeCycle mReceiver;

MyLifeCycle_LifecycleAdapter(MyLifeCycle receiver) {
    this.mReceiver = receiver;
}

public void callMethods(LifecycleOwner owner, Event event, boolean onAny, MethodCallsLogger logger) {
    boolean hasLogger = logger != null;
    if (!onAny) {
        if (event == Event.ON_CREATE) {
            if (!hasLogger || logger.approveCall("onCreate", 1)) {
                this.mReceiver.onCreate();
            }

        }
    }
}
}

在生成MyLifeCycle_LifecycleAdapter 类的callMethods方法中会调用我们的MyLifecycle的方法 this.mReceiver.onCreate(),那么callMethods方法在哪触发呢?我么看看LifecycleRegistry .addObserver方法:

@Override
public void addObserver(@NonNull LifecycleObserver observer) {

    //1
    ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
 //2
    ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);

   //省略...........................
}

上面代码主要是将observer保存在mObserverMap中,并计算当前的状态。接下我们看看触发生命周期的方法,首先我们定义了LifecycleRegistry 并使用 LifecycleRegistry .handleLifecycleEvent(mEvent)方法对生命周期的事件进行分发,代码如下:

public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
    State next = getStateAfter(event);
    moveToState(next);
}

方法很简单,我们主要看moveToState,意思是改变状态,代码如下:

 private void moveToState(State next) {
    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;
}

这个方法比较简单,主要是对状态进行判断,接着我么来看看sync()方法,比较重要,代码如下:

private void sync() {
    LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
    if (lifecycleOwner == null) {
        throw new IllegalStateException("LifecycleOwner of this LifecycleRegistry is already"
                + "garbage collected. It is too late to change lifecycle state.");
    }
    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);//1
        }
        Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
        if (!mNewEventOccurred && newest != null
                && mState.compareTo(newest.getValue().mState) > 0) {
            forwardPass(lifecycleOwner);//2
        }
    }
    mNewEventOccurred = false;
}

在sync方法中我们主要看backwardPass方法的实现:

 private void backwardPass(LifecycleOwner lifecycleOwner) {
    Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
            mObserverMap.descendingIterator();
    while (descendingIterator.hasNext() && !mNewEventOccurred) {
        Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
        ObserverWithState observer = entry.getValue();
        while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
                && mObserverMap.contains(entry.getKey()))) {
            Event event = downEvent(observer.mState);
            pushParentState(getStateAfter(event));
            observer.dispatchEvent(lifecycleOwner, event);//1
            popParentState();
        }
    }
}

在我注释1处,看到了 observer.dispatchEvent(lifecycleOwner, event),这个方法处于ObserverWithState 类方法,多生命周期事件进行了分发,如下代码

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 = getStateAfter(event);
        mState = min(mState, newState);
        mLifecycleObserver.onStateChanged(owner, event);
        mState = newState;
    }
}

在ObserverWithState 的构造方法中我们主要看看mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer)这行代码,实现如下:

@NonNull
static LifecycleEventObserver lifecycleEventObserver(Object 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);      
}

在lifecycleEventObserver方法中object参数就是我们定义实现了LifecycleObserver接口的MyLifecycle对象,并且通过这个对象去拿到构造方法,实际上是通过拼接_LifecycleAdapter拿到MyLifeCycle_LifecycleAdapter 对象,并创建了GeneratedAdapter对象并把MyLifecycle对象当做参数传进去。

在上MyLifecycle生成类的代码:

public class MyLifeCycle_LifecycleAdapter implements GeneratedAdapter {
final MyLifeCycle mReceiver;

MyLifeCycle_LifecycleAdapter(MyLifeCycle receiver) {
    this.mReceiver = receiver;
}

public void callMethods(LifecycleOwner owner, Event event, boolean onAny, MethodCallsLogger logger) {
    boolean hasLogger = logger != null;
    if (!onAny) {
        if (event == Event.ON_CREATE) {
            if (!hasLogger || logger.approveCall("onCreate", 1)) {
                this.mReceiver.onCreate();
            }

        }
    }
}
}

最后在ObserverWithState.dispatchEvent方法中调用了 mLifecycleObserver.onStateChanged(owner, event)方法,也就是定义的MyLifecycle类生成的MyLifeCycle_LifecycleAdapter 类的onStateChanged方法,最终会调用我们的MyLifecycle的onCreate()方法,最后在看一下具体的流程图:


lifecycle.png
上一篇下一篇

猜你喜欢

热点阅读