JetPacks之Lifecycles原理

JetPacks之Lifecycles原理
项目资源
UML 时序图

读懂这里,查看下一篇 LiveDataBus
下一篇LiveData

预备知识点

「观察者模式- 反射 - 注解」

源码结构

Lifecycle 类是abstract

  -> 留意一下这几个状态,下面会有用
 public enum Event {
    /**
     * Constant for onCreate event of the {@link LifecycleOwner}.
     */
    ON_CREATE,
    /**
     * Constant for onStart event of the {@link LifecycleOwner}.
     */
    ON_START,
    /**
     * Constant for onResume event of the {@link LifecycleOwner}.
     */
    ON_RESUME,
    /**
     * Constant for onPause event of the {@link LifecycleOwner}.
     */
    ON_PAUSE,
    /**
     * Constant for onStop event of the {@link LifecycleOwner}.
     */
    ON_STOP,
    /**
     * Constant for onDestroy event of the {@link LifecycleOwner}.
     */
    ON_DESTROY,
    /**
     * An {@link Event Event} constant that can be used to match all events.
     */
    ON_ANY
}


public enum State {
    
    DESTROYED,

    INITIALIZED,

    CREATED,

    STARTED,

    RESUMED;

    public boolean isAtLeast(@NonNull State state) {
        return compareTo(state) >= 0;
    }
}

看下我们的Activity 的关系

AppCompatActivity extends FragmentActivity implements AppCompatCallback,
    TaskStackBuilder.SupportParentable, ActionBarDrawerToggle.DelegateProvider 
...
public class FragmentActivity extends ComponentActivity implements
    ActivityCompat.OnRequestPermissionsResultCallback,
    ActivityCompat.RequestPermissionsRequestCodeValidator {
...

public class ComponentActivity extends androidx.core.app.ComponentActivity implements
    LifecycleOwner,
    ViewModelStoreOwner,
    SavedStateRegistryOwner,
    OnBackPressedDispatcherOwner {
...

【自定义测试代码】用一段测试代码作为入口点,查看我们的源代码

public class NameActivity extends AppCompatActivity {

private NameViewModel model;

private TextView nameTextView;
private Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_name);
    nameTextView=findViewById(R.id.tvText);
    btn=findViewById(R.id.btn);

    model= ViewModelProviders.of(this).get(NameViewModel.class);

    //需要一个观察者来观察数据
    Observer observer=new Observer(){
        @Override
        public void onChanged(String s) {
            nameTextView.setText(s);
        }
    };

    //订阅
    model.getCurrentName().observe(this,observer);

    btn.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            String anotherName="Jetpack"+(model.i++);
            model.getCurrentName().setValue(anotherName);
        }
    });

}

}

看下我们activity_name 布局,为了方便我们就按照最简单的来写






我们来找到两个阅读源码的入口点

    //订阅
    ->  源码入口点1
    model.getCurrentName().observe(this,observer);

    btn.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            String anotherName="Jetpack"+(model.i++);
            ->  源码入口点2
            model.getCurrentName().setValue(anotherName);
        }
    });

记录好这两个入口使用点,我们回头再来看这里

进入 源码ComponentActivity

构造方法:

我们知道有一个兼容处理

ComponentActivity()  {   
...
if (19 <= SDK_INT && SDK_INT <= 23) {
        getLifecycle().addObserver(new ImmLeaksCleaner(this));
    }
}

真正重要的是onCreate

-> 关注一下「ReportFragment」
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    ...
    ReportFragment.injectIfNeededIn(this);
    ...
}

ReportFragment

进入方法我们看到,和Glide等源码框架思路一致,创建一个没有布局的fragment

public static void injectIfNeededIn(Activity activity) {
    if (Build.VERSION.SDK_INT >= 29) {
        // On API 29+, we can register for the correct Lifecycle callbacks directly
        activity.registerActivityLifecycleCallbacks(
                new LifecycleCallbacks());
    }
   
    android.app.FragmentManager manager = activity.getFragmentManager();
    if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
        manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
        // Hopefully, we are the first to make a transaction.
        manager.executePendingTransactions();
    }
}

进入初始化方法查看

  -> 关注一下源代码 「分发事件 」dispatch(Lifecycle.Event.xxx)
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    dispatchCreate(mProcessListener);
    dispatch(Lifecycle.Event.ON_CREATE);
}

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

@Override
public void onResume() {
    super.onResume();
    dispatchResume(mProcessListener);
    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);
    // just want to be sure that we won't leak reference to an activity
    mProcessListener = null;
}

我们进入dipatch方法一探究竟「可能29+ 走的是回调结构,但差不多」

-> 发现最终都是走的 handleLifecycleEvent,进入方法看看
    
@SuppressWarnings("deprecation")
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);
        }
    }
}

handleLifecycleEvent

public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
    -> 拿到下一个周期的状态,并将状态移动
    State next = getStateAfter(event);
    -> 移动到下一个状态,分别进入这两个方法查看一下
    moveToState(next);
}

getStateAfter(event) ------------------------>

-> 看到下面代码状态对应的值,相信都能看懂
static State getStateAfter(Event event) {
    switch (event) {
        case ON_CREATE:
        case ON_STOP:
            return CREATED;
        case ON_START:
        case ON_PAUSE:
            return STARTED;
        case ON_RESUME:
            return RESUMED;
        case ON_DESTROY:
            return DESTROYED;
        case ON_ANY:
            break;
    }
    throw new IllegalArgumentException("Unexpected event value " + event);
}

来一张图描述


时序图

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

在这个各方发里面,如上图某个状态的,对应的会有 backwardPass(lifecycleOwner),forwardPass(lifecycleOwner);
当前处于的状态和程序目标状态同步出现差异,会进行移动

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);
        }
        Entry newest = mObserverMap.newest();
        if (!mNewEventOccurred && newest != null
                && mState.compareTo(newest.getValue().mState) > 0) {

            -> 关注这两个方法实现差不多,随便找一个点进去查看==

            forwardPass(lifecycleOwner);
        }
    }
    mNewEventOccurred = false;
}

forwardPass----------------->dispatchEvent

    private void forwardPass(LifecycleOwner lifecycleOwner) {
    Iterator> ascendingIterator =
            mObserverMap.iteratorWithAdditions();
    while (ascendingIterator.hasNext() && !mNewEventOccurred) {
        Entry entry = ascendingIterator.next();
        ObserverWithState observer = entry.getValue();
        while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
                && mObserverMap.contains(entry.getKey()))) {
            pushParentState(observer.mState);

            -> dispatchEvent 关键看下这个

            observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
            popParentState();
        }
    }
}

你会发现走了一个静态内部类回调-----》onStateChanged

static class ObserverWithState {
    。。。

    void dispatchEvent(LifecycleOwner owner, Event event) {
        State newState = getStateAfter(event);
        mState = min(mState, newState);
        -> 注意跟踪这里
        mLifecycleObserver.onStateChanged(owner, event);
        mState = newState;
    }
}

调用了【实现接口的方法类】

class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
private final Object mWrapped;
private final CallbackInfo mInfo;

ReflectiveGenericLifecycleObserver(Object wrapped) {
    mWrapped = wrapped;
    mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}

@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Event event) {
    mInfo.invokeCallbacks(source, event, mWrapped);
}

}

进入构造方法,你会看到重要的一句

        OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);

这就是我们卸载自己的周期函数上的类注解。我们通过APT 反射方法获取相关详情

执行反射onStateChanged

承接最开始,我们记录的。
-> 源码入口点1
model.getCurrentName().observe(this,observer);

跟进去,我们会看程序进入onStateChange

observe->owner.getLifecycle().addObserver(wrapper);
->addObserver

pushParentState(statefulObserver.mState);
->        statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
        popParentState();

-> mLifecycleObserver.onStateChanged(owner, event);

进入 ReflectiveGenericLifecycleObserver

-> 源码入口点2
model.getCurrentName().setValue(anotherName);

@MainThread
protected void setValue(T value) {
    assertMainThread("setValue");
    mVersion++;
    mData = value;
    dispatchingValue(null);
}

跟进

void dispatchingValue(@Nullable ObserverWrapper initiator) {
    if (mDispatchingValue) {
        mDispatchInvalidated = true;
        return;
    }
    mDispatchingValue = true;
    do {
        mDispatchInvalidated = false;
        if (initiator != null) {
            -> 关键看这个点
            considerNotify(initiator);
            initiator = null;
        } else {
            for (Iterator, ObserverWrapper>> iterator =
                    mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
                  -> 关键看这个点
                considerNotify(iterator.next().getValue());
                if (mDispatchInvalidated) {
                    break;
                }
            }
        }
    } while (mDispatchInvalidated);
    mDispatchingValue = false;
}

看下重要的version比对点,最终调用onChange 接口,我们自己的实现。整个观察者闭环走完

private void considerNotify(ObserverWrapper observer) {
    if (!observer.mActive) {
        return;
    }
    // Check latest state b4 dispatch. Maybe it changed state but we didn't get the event yet.
    //
    // we still first check observer.active to keep it as the entrance for events. So even if
    // the observer moved to an active state, if we've not received that event, we better not
    // notify for a more predictable notification order.
    if (!observer.shouldBeActive()) {
        observer.activeStateChanged(false);
        return;
    }
    if (observer.mLastVersion >= mVersion) {
        return;
    }
    observer.mLastVersion = mVersion;
    observer.mObserver.onChanged((T) mData);
}

你可能感兴趣的:(JetPacks之Lifecycles原理)