美文网首页
Jetpack-Lifecycle

Jetpack-Lifecycle

作者: shiyuzhe | 来源:发表于2019-03-01 13:03 被阅读1次

    痛点,Lifecycle解决了什么

    MVP中的presenter感知activity或者fragment的生命周期需要。

    框架和结构

    • 使用的是观察者模式
    • activity和fragment内部实现LifecycleOwner接口
    • 要感知activity和fragment生命周期的部分实现LifecycleObserver接口
    • lifecycle.addObserver(LifecycleObserver)
    • activity和fragment生命周期的改变实时传递给观察者

    LifecycleOwner

    public interface LifecycleOwner {
    @NonNull Lifecycle getLifecycle();}
    Fragment implements LifecycleOwner
    AppCompatActivity extends FragmentActivity extends ComponentActivity implements LifecycleOwner
    

    Lifecycle

    public abstract class Lifecycle {
    @MainThread
    public abstract void addObserver(@NonNull LifecycleObserver observer);
    @MainThread
    public abstract void removeObserver(@NonNull LifecycleObserver observer);
    @MainThread
    @NonNull
    public abstract State getCurrentState();
    
    @SuppressWarnings("WeakerAccess")
    public enum Event {
        ON_CREATE,
        ON_START,
        ON_RESUME,
        ON_PAUSE,
        ON_STOP,
        ON_DESTROY,//Constant for onXXX event of the {@link LifecycleOwner}.
        ON_ANY//An {@link Event Event} constant that can be used to match all events.
    }
    //Lifecycle states. You can consider the states as the nodes in a graph and {@link Event}s as the edges between these nodes.
    @SuppressWarnings("WeakerAccess")
    public enum State {
        DESTROYED,//for an Activity, this state is reached right before Activity's onDestroy call.
        INITIALIZED,//...,this is the state when it is constructed but has not received onCreate yet.
        CREATED,//this state is reached in two cases:after onCreate call&right before onStop call
        STARTED, //this state is reached in two cases:after onStart call&right before onPause call
        RESUMED;//...,this state is reached after onResume is called.
        public boolean isAtLeast(@NonNull State state) {
            return compareTo(state) >= 0;
        }
    }}
    

    LifecycleObserver

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

    源码

    LifecycleOwner的改变怎么传递给LifecycleObserver?

    起点mLifecycleOwner

    LifecycleRegistry

    继承自Lifecycle,Lifecycle的唯一实现类

    class LifecycleRegistry extends Lifecycle{
    ...
    @Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
        //构建ObserverWithState并存入mObserverMap,如果observer已存在则返回value,previous不空。
        if (previous != null) {
            return;
        }
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
        if (lifecycleOwner == null) {
            // it is null we should be destroyed. Fallback quickly
            return;
        }
        ...
        //去掉state相关代码
        if (!isReentrance) {
            // we do sync only on the top level.
            sync();
        }
    }
    // 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;
        }
        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);
            }
            Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }
    ...
    }
    

    再往下就是FullLifecycleObserverAdapter中的onStateChanged,
    再到LifecycleObserver的实现类 ,头疼 呆会再来看

    相关文章

      网友评论

          本文标题:Jetpack-Lifecycle

          本文链接:https://www.haomeiwen.com/subject/lyvruqtx.html