Android Jetpack之Lifecycles + LiveData探索

您所在的位置:网站首页 lifecycles Android Jetpack之Lifecycles + LiveData探索

Android Jetpack之Lifecycles + LiveData探索

#Android Jetpack之Lifecycles + LiveData探索| 来源: 网络整理| 查看: 265

目录 总览类图关系生命周期事件的分发如何观察生命周期变化LiveData使用及原理分析添加观察者发送数据总结

总览

  实现一种可感知生命周期的观察者模式。在Activity或者Fragment中的生命周期回调函数中去发起事件,通知观察者。官方给出的最佳实践方案即LiveData。

类图关系

  分为3个模块,Lifecycle、LifecycleOwner、LifecycleObserver: Lifecycle类图   先做一个全局的分析。LifecycleOwner即生命周期的持有者,系统中的实现就是Fragment和SupporActivityComponentActivity ,它们都持有一个LifecycleRegister对象,会在各个生命周期函数中去调用LifecycleRegister的相应Api发起生命周期变化的事件Lifecycle.Event,随即计算出下一步的状态Lifecycle.State。

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 } /** * 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 state for a LifecycleOwner. After this event, this Lifecycle will not dispatch * any more events. For instance, for an {@link android.app.Activity}, this state is reached * right before Activity's {@link android.app.Activity#onDestroy() onDestroy} call. */ DESTROYED, /** * Initialized state for a LifecycleOwner. For an {@link android.app.Activity}, this is * the state when it is constructed but has not received * {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} yet. */ INITIALIZED, /** * Created state for a LifecycleOwner. For an {@link android.app.Activity}, this state * is reached in two cases: * * after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call; * right before {@link android.app.Activity#onStop() onStop} call. * */ CREATED, /** * Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state * is reached in two cases: * * after {@link android.app.Activity#onStart() onStart} call; * right before {@link android.app.Activity#onPause() onPause} call. * */ STARTED, /** * Resumed state for a LifecycleOwner. For an {@link android.app.Activity}, this state * is reached after {@link android.app.Activity#onResume() onResume} is called. */ RESUMED; /** * Compares if this State is greater or equal to the given {@code state}. * * @param state State to compare with * @return true if this State is greater or equal to the given {@code state} */ public boolean isAtLeast(@NonNull State state) { return compareTo(state) >= 0; } }

  下边贴一张Goolge官方的图,把event比作边,state比作点。这样在生命周期发生变化时发出对应的事件,然后再根据当前的状态确定下一个变化的状态。 lifecycle-states   LifecycleRegistry中持有所有的LifecycleObserver对象,当收到生命周期变化的事件后就会尝试通知所有的LifecycleObserver,最终会回调LifecycleObserver.onStateChanged(LifecycleOwner source, Lifecycle.Event event)函数。

生命周期事件的分发 ComponentActivity中进行分发 protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mSavedStateRegistryController.performRestore(savedInstanceState); ReportFragment.injectIfNeededIn(this); if (mContentLayoutId != 0) { setContentView(mContentLayoutId); } }

  在onCreate方法中,调用了ReportFragment.injectIfNeededIn(this), 生命周期事件的分发就是通过这个ReportFragment来进行代理的。injectIfNeededIn方法很简单就是向Activity中添加fragment。

public static void injectIfNeededIn(Activity activity) { android.app.FragmentManager manager = activity.getFragmentManager(); if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) { manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit(); manager.executePendingTransactions(); } }

  接下来看ReportFragment到底是如何分发生命周期事件的

public class ReportFragment extends Fragment { @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; } private void dispatch(Lifecycle.Event event) { Activity activity = getActivity(); if (activity instanceof LifecycleOwner) { Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle(); if (lifecycle instanceof LifecycleRegistry) { ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event); } } } }

  我们可以看到在各个生命周期函数中都调用了dispatch方法发起对应生命周期的事件。而dispatch方法也很简单,最终回调了LifecycleRegistry的handleLifecycleEvent方法。

public void handleLifecycleEvent(@NonNull Lifecycle.Event event) { //根据事件去计算下一个状态 State next = getStateAfter(event); moveToState(next); } //这个方法对照着上边那张生命周期变化的图就可以很好理解 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); } private void moveToState(State next) { if (mState == next) { return; } //更新状态 mState = next; mHandlingEvent = true; //同步LifeCycleRegistry中的Observer的状态 sync(); mHandlingEvent = false; }

  关键代码sync()。

private void sync() { LifecycleOwner lifecycleOwner = mLifecycleOwner.get(); while (!isSynced()) { //当前LifeCycleRegistry的状态小于最早添加的observer状态,就进行后向遍历 //由于状态State是一个枚举变量,所以在前边定义的状态就“小于”后边定义的状态 if (mState.compareTo(mObserverMap.eldest().getValue().mState) forwardPass(lifecycleOwner); } } }

  前向遍历和后向遍历逻辑差不多,这里只分析一个。forwardPass 每次只能更新一个状态,不能跳跃的进行变化。 比如当前LifecycleRegistry的state为RESUMED,observer的state为INITIALIZED,那么变换的过程只能是INITIALIZED -> CREATED -> STARTED -> RESUMED。 最终经过3次变化才能和LifecycleRegistry状态保持一致。LiveData中对状态变化还做了额外的处理,保证了在上诉过程中最多通知用户一次,这在后边会进行分析。

private void forwardPass(LifecycleOwner lifecycleOwner) { //保留核心代码 Iterator ascendingIterator = mObserverMap.iteratorWithAdditions(); while (ascendingIterator.hasNext()) { Entry entry = ascendingIterator.next(); ObserverWithState observer = entry.getValue(); while ((observer.mState.compareTo(mState) State newState = getStateAfter(event); mState = min(mState, newState); //通知LiveData中管理的observer,最后会回调用户自己添加的observer.onchanged mLifecycleObserver.onStateChanged(owner, event); mState = newState; } //用于计算从当前状态变换到后一个状态需要的事件 private static Event upEvent(State state) { switch (state) { case INITIALIZED: case DESTROYED: return ON_CREATE; case CREATED: return ON_START; case STARTED: return ON_RESUME; case RESUMED: throw new IllegalArgumentException(); } throw new IllegalArgumentException("Unexpected state value " + state); }

  用一个流程图来总结生命周期事件的传递流程: 生命周期事件传递   这里补充分析一下LiveData是怎么在生命周期状态变换中保证最多一次通知的。对于LiveData内部的LifecycleBoundObserver来说,它只有两种状态:激活(mActive = true)或者非激活(mActive = false),系统默认的实现是只有LifecycleOwner处于STARTED或者RESUMED两个状态时mActive才为true,了解这个原理后对照下边的源码就很容易理解为什么能保证最多一次通知了:

void activeStateChanged(boolean newActive) { if (newActive == mActive) { return; } mActive = newActive; boolean wasInactive = LiveData.this.mActiveCount == 0; LiveData.this.mActiveCount += mActive ? 1 : -1; if (wasInactive && mActive) { onActive(); } if (LiveData.this.mActiveCount == 0 && !mActive) { onInactive(); } if (mActive) { dispatchingValue(this); } }

  关键就是第一个if语句的判断,只有激活状态改变才会执行后续的逻辑。举个例子: LifecycleOwner从CREATED —ON_START—> STARTED —ON_RESUME—> RESUMED,经历了两次状态的改变,但对于LifecycleBoundObserver来说就变化了一次,CREATED —ON_START—> STARTED时,从mActive = false -> mActive = true,后续STARTED —ON_RESUME—> RESUMED对于LifecycleBoundObserver来说都处于激活状态,所以就不会再执行后续逻辑进行通知了。 2. Fragment中的分发   大致流程和上边一样,主要看分发的入口,直接在自己的生命周期函数中进行回调

void performCreate(Bundle savedInstanceState) { mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE); } void performStart() { if (mView != null) { mViewLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START); } } 如何观察生命周期变化 方式1(官方推荐):通过注解进行监听 public class MyActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); getLifecycle().addObserver(new LifecycleObserver() { @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) public void onResume() { Log.d("lifecycle", "event ->" + Lifecycle.Event.ON_RESUME); } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) public void onPause() { Log.d("lifecycle", "event ->" + Lifecycle.Event.ON_PAUSE); } }); } } 方式2(随着androidx库的推进,该类有可能废弃):通过实现LifecycleEventObserver接口来监听 public class Activity2 extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); getLifecycle().addObserver( (LifecycleEventObserver) (source, event) -> Log.d("lifecycle" ,"event ->" + event) ); } } 方式3:通过LiveData来间接进行观察,生命周期的变化会被LiveData内部进行观察,不会直接回调给用户。LiveData只会把”可见“状态下的事件变化回调给用户。基于此实现,LiveData才能够只在Activity/Fragment处于可见状态时通知用户去刷新数据。 LiveData使用及原理分析 添加观察者 class NameActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val liveData = MutableLiveData() // Create the observer which updates the UI. val nameObserver = Observer { newName -> // Update the UI, in this case, a TextView. mNameTextView.text = newName } // Observe the LiveData, passing in this activity as the LifecycleOwner and the observer. liveData.observe(this, nameObserver) } }

  关键代码liveData.observe(this, nameObserver),跟进一下源码:

private SafeIterableMap mObservers = new SafeIterableMap(); @MainThread public void observe(@NonNull LifecycleOwner owner, @NonNull Observer observer) { if (owner.getLifecycle().getCurrentState() == DESTROYED) { // ignore return; } LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer); ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper); //同一个observer只能绑定一个lifecycleOwner if (existing != null && !existing.isAttachedTo(owner)) { throw new IllegalArgumentException("Cannot add the same observer" + " with different lifecycles"); } if (existing != null) { return; } owner.getLifecycle().addObserver(wrapper); }

  对用户传入的 Observer 封装为其内部的一个类 LifecycleBoundObserver 并保存于内部的一个 map中,随后调用LifecycleRegistry的addObserver(wrapper) 方法进行观察者的添加。Observer是暴露给用户使用的,该接口非常简单:

public interface Observer { void onChanged(@Nullable T t); }

  Observer会被封装到LifecycleBoundObserver对象中去,这一层封装持有了三个比较重要的属性:

LifecycleOwner mOwner //生命周期的持有者,需要通过它来判断当前的状态,来决定是否通知用户Observer


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3