LiveData LiveData是一个可以被观察的数据持有类,可以感知并遵循Activity、Fragment等组件的生命周期。因此可以做到仅再组件处于生命周期的激活状态时更新UI数据。
注册 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 @MainThread public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) { assertMainThread("observe"); if (owner.getLifecycle().getCurrentState() == DESTROYED) { // ignore return; } //对observer进行封装,observer不具备生命周期,而LifecycleBoundObserver是一个内部类,实现了观察者接口的对象,可以观察生命周期。 LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer); ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper); if (existing != null && !existing.isAttachedTo(owner)) { throw new IllegalArgumentException("Cannot add the same observer" + " with different lifecycles"); } if (existing != null) { return; } // 把wrapper观察者给生命周期,同时调用的LifecycleRegistry的addObserver owner.getLifecycle().addObserver(wrapper); } // LifecycleRegistry有一个mObserverMap,保存了所有的ObserverWrapper。 public class LifecycleRegistry extends Lifecycle { private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap = new FastSafeIterableMap<>(); } class LifecycleBoundObserver extends ObserverWrapper implements GenericLifecycleObserver { @NonNull final LifecycleOwner mOwner; LifecycleBoundObserver(@NonNull LifecycleOwner owner, Observer<? super T> observer) { super(observer); mOwner = owner; } @Override boolean shouldBeActive() { return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED); } @Override public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) { if (mOwner.getLifecycle().getCurrentState() == DESTROYED) { // 当activity销毁时,清除mObserver removeObserver(mObserver); return; } activeStateChanged(shouldBeActive()); } @Override boolean isAttachedTo(LifecycleOwner owner) { return mOwner == owner; } @Override void detachObserver() { mOwner.getLifecycle().removeObserver(this); } }
postValue postValue,时通过Handler的方式,在子线程刷新数据。
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 public class MutableLiveData<T> extends LiveData<T> { // 用于子线程数据的刷新 @Override public void postValue(T value) { super.postValue(value); } @Override public void setValue(T value) { super.setValue(value); } } protected void postValue(T value) { boolean postTask; synchronized (mDataLock) { postTask = mPendingData == NOT_SET; mPendingData = value; } if (!postTask) { return; } ArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable); } public void postToMainThread(Runnable runnable) { if (mMainHandler == null) { synchronized (mLock) { if (mMainHandler == null) { mMainHandler = new Handler(Looper.getMainLooper()); } } } //noinspection ConstantConditions mMainHandler.post(runnable); }
setValue 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 @MainThread protected void setValue(T value) { assertMainThread("setValue"); mVersion++;//数据版本+1 mData = value; dispatchingValue(null);//数据分发 } // mDispatchInvalidated 是在递归操作中的容错机制,比如一个livedata多次setValue值,第二次应该是后一次的值 private void dispatchingValue(@Nullable ObserverWrapper initiator) { if (mDispatchingValue) { mDispatchInvalidated = true; return; } mDispatchingValue = true; // while循环,处理所有的观察者 do { mDispatchInvalidated = false; if (initiator != null) { considerNotify(initiator); initiator = null; } else { for (Iterator<Map.Entry<Observer<? super T>, ObserverWrapper>> iterator = mObservers.iteratorWithAdditions(); iterator.hasNext(); ) { considerNotify(iterator.next().getValue()); if (mDispatchInvalidated) { break; } } } } while (mDispatchInvalidated); mDispatchingValue = false; } private void considerNotify(ObserverWrapper observer) { if (!observer.mActive) {//界面是否处于可见状态 return; } if (!observer.shouldBeActive()) { observer.activeStateChanged(false); return; } if (observer.mLastVersion >= mVersion) {//如果注册的版本>数据版本也返回。 return; } observer.mLastVersion = mVersion; //noinspection unchecked observer.mObserver.onChanged((T) mData);//界面刷新 }
activity生命周期change数据 CustomerActivity -》AppCompatActivity-》FragmentActivity-》ComponentActivity 而在》ComponentActivity中,添加了一个默认ReportFragment,
1 2 3 4 protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ReportFragment.injectIfNeededIn(this); }
而这个ReportFragment监听了生命周期:
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 @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; }
dispatch会触发相应handleLifecycleEvent的事件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 private void dispatch(Lifecycle.Event event) { Activity activity = getActivity(); 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); } } }
会到LifecycleRegistry里执行:moveToState->sync->forwardPass->observer.dispatchEvent
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 67 68 69 70 71 72 73 74 public void handleLifecycleEvent(@NonNull Lifecycle.Event event) { State next = getStateAfter(event); moveToState(next); } private void sync() { LifecycleOwner lifecycleOwner = mLifecycleOwner.get(); // 循环调用forwardPass 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); } } } // LifecycleRegistry有一个mObserverMap,遍历所有的Observer private void forwardPass(LifecycleOwner lifecycleOwner) { Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator = mObserverMap.iteratorWithAdditions(); while (ascendingIterator.hasNext() && !mNewEventOccurred) { Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next(); ObserverWithState observer = entry.getValue(); while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred && mObserverMap.contains(entry.getKey()))) { pushParentState(observer.mState); //这里就进入到了观察者了 observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState)); popParentState(); } } } static class ObserverWithState { State mState; GenericLifecycleObserver mLifecycleObserver; ObserverWithState(LifecycleObserver observer, State initialState) { mLifecycleObserver = Lifecycling.getCallback(observer); mState = initialState; } void dispatchEvent(LifecycleOwner owner, Event event) { State newState = getStateAfter(event); mState = min(mState, newState); ////这里执行的不就是我们注册时候的Observer吗?也就是LifecycleBoundObserver extend ObserverWrapper,那执行onStateChanged,也就是执行LifecycleBoundObserver.onStateChanged,这样就 执行activeStateChanged mLifecycleObserver.onStateChanged(owner, event); mState = newState; } } //dispatchingValue执行的不就是setValue的dispatchingValue 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);// 处于活动状态,刷新数据。 } }
事件分发
LiveData 数据存储 private volatile Object mData = NOT_SET;// 就是livedata对象的一个变量 那何时销毁的。肯定时在生命周期里
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 // LifecycleBoundObserver里 @Override public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) { if (mOwner.getLifecycle().getCurrentState() == DESTROYED) {//界面销毁时 removeObserver(mObserver); return; } activeStateChanged(shouldBeActive()); } public void removeObserver(@NonNull final Observer<? super T> observer) { ObserverWrapper removed = mObservers.remove(observer);//livedata跟lifecycle生命周期接触绑定,livedata就时一个独立的对象,就是GCRoot引用不到了,GC会自动回收 if (removed == null) { return; } removed.detachObserver(); removed.activeStateChanged(false); }
volatile Livedata在主线程和子线程都可以用,如果多个线程同时处理同一个mData,所以会存在并发的问题。而mData时一个变量,所以用volatile。 线程处理变量是在自己的工作内存,用完后写回主内存。如果多个线程同时处理这个动作,就是volatile要解决的问题。当一个线程要处理时,另一个线程也在执行,就要等这个线程写回主内存后,在从主内存拷贝到工作线程执行。所以volatile保持了原子性。
LiveData粘性事件 产生原因:先发送消息,后注册。也就是下边的版本判断:
1 2 3 if (observer.mLastVersion >= mVersion) {//如果注册的版本>数据版本也返回。 return; }
反射解决 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 private void hook(@NonNull Observer<T> observer) throws Exception { //get wrapper's version Class<LiveData> classLiveData = LiveData.class; Field fieldObservers = classLiveData.getDeclaredField("mObservers"); fieldObservers.setAccessible(true); Object objectObservers = fieldObservers.get(this); Class<?> classObservers = objectObservers.getClass(); Method methodGet = classObservers.getDeclaredMethod("get", Object.class); methodGet.setAccessible(true); Object objectWrapperEntry = methodGet.invoke(objectObservers, observer); Object objectWrapper = null; if (objectWrapperEntry instanceof Map.Entry) { objectWrapper = ((Map.Entry) objectWrapperEntry).getValue(); } if (objectWrapper == null) { throw new NullPointerException("Wrapper can not be bull!"); } Class<?> classObserverWrapper = objectWrapper.getClass().getSuperclass(); Field fieldLastVersion = classObserverWrapper.getDeclaredField("mLastVersion"); fieldLastVersion.setAccessible(true); //get livedata's version Field fieldVersion = classLiveData.getDeclaredField("mVersion"); fieldVersion.setAccessible(true); Object objectVersion = fieldVersion.get(this); //set wrapper's version fieldLastVersion.set(objectWrapper, objectVersion); } }
忽略第一次onChanged回调 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 /** * 包装observer。可以忽略第一次的onChanged回调 * @param <T> */ private class ObserverWrapper<T> implements Observer<T> { private final Observer targetObserver; private boolean ignoreOnce; public ObserverWrapper(Observer targetObserver) { this.targetObserver = targetObserver; this.ignoreOnce = getValue() != null; } @Override public void onChanged(T t) { if (ignoreOnce) { ignoreOnce = false; } else { targetObserver.onChanged(t); } } }
常用通信框架
方案
优点
缺点
Handler
系统原生,能实现线程间通信
高耦合、不利于维护、容易导致内存泄漏和空指针
BroadCast
简单
性能差、传递数据有限、打乱代码执行逻辑
interface
速度快、容易理解
实现复杂、不利于维护
RxBus
效率高、无内存泄漏
基于rxjava,学习成本高且依赖包太大
EventBus
使用简单
混淆问题,无法感知组件的生命周期、实现复杂
Lifecycle 概述 在真实的app中,最终会有大量的管理界面和其他组件的调用,以响应生命周期的当前状态。管理多个组件会在生命周期方法中放置大量的代码,这使得它们就难以维护。 androidx.lifecycle 软件包提供了可用于构建生命周期感知型组件的类和接口 - 这些组件可以根据 Activity 或 Fragment 的当前生命周期状态自动调整其行为。
原理 观察者设计模式(发布-订阅)。
注册 在activity中:1 getLifecycle().addObserver(new LifecycleObserver() {});
getLifecycle()获取的是ComponentActivity中的LifecycleRegistry
1 private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
所以addObserver也是LifecycleRegistry的addObserver,从而把observer存到容器mObserverMap中,mObserverMap是一个Map。所以,注册完成 。
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 public void addObserver(@NonNull LifecycleObserver observer) { State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED; ObserverWithState statefulObserver = new ObserverWithState(observer, initialState); ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver); // 如果observer之前已经传进来了,则直接返回,不重复添加 if (previous != null) { return; } LifecycleOwner lifecycleOwner = mLifecycleOwner.get(); if (lifecycleOwner == null) { // it is null we should be destroyed. Fallback quickly // 如何lifecycleOwner已经被回收了,直接返回 return; } boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent; State targetState = calculateTargetState(observer); mAddingObserverCounter++; while ((statefulObserver.mState.compareTo(targetState) < 0 && mObserverMap.contains(observer))) { pushParentState(statefulObserver.mState); statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState)); popParentState(); // mState / subling may have been changed recalculate targetState = calculateTargetState(observer); } if (!isReentrance) { // we do sync only on the top level. sync(); } mAddingObserverCounter--; }
轮询通知 在发生生命周期是,都会执行到LifecycleRegistry的handleLifecycleEvent方法:
-> moveToState-> sync-> forwardPass/backwardPass->observer.dispatchEvent->mLifecycleObserver.onStateChanged(owner, event);
1 2 3 4 public void handleLifecycleEvent(@NonNull Lifecycle.Event event) { State next = getStateAfter(event); moveToState(next); }
那handleLifecycleEvent,是如何被执行的?其实是通过一个默认的ReportFragment,这个Fragment响应着Activity的每个生命周期。ComponentActivity中:
1 2 3 4 protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ReportFragment.injectIfNeededIn(this); }
ReportFragment中的生命周期都调用了dispatch,而dispatch中就调用了handleLifecycleEvent
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 static void injectIfNeededIn(Activity activity) { // ProcessLifecycleOwner should always correctly work and some activities may not extend // FragmentActivity from support lib, so we use framework fragments for activities 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(); } } @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 LifecycleRegistryOwner) { ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event); return; } if (activity instanceof LifecycleOwner) { Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle(); if (lifecycle instanceof LifecycleRegistry) { ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event); } } }
所以如上就指导执行生命周期时如何轮询observer容器,也就是LifecycleRegistry中的map,从而通知观察者响应了。 这个思路其实采用的时Glide的设计思想,所以Glide中view拥有生命周期的思想,也是这个思想。
Activity&Fragment生命周期 那Activity执行生命周期时如果通知到Fragment中的。在Activity中,
1 2 3 4 5 6 7 8 9 10 final void performResume(boolean followedByPause, String reason) { performRestart(true /* start */, reason); // mResumed is set by the instrumentation //执行Activity的OnResume生命周期后 mInstrumentation.callActivityOnResume(this); 。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。 //执行Activity内的F绕过门头的OnResume生命周期 mFragments.dispatchResume(); mFragments.execPendingActions(); }
接着执行 -> FragmentController.dispatchResume -> FragmentManager.dispatchResume -> dispatchMoveToState -> moveToState -> for(moveFragmentToExpectedState) -> moveToState(Fragment f) -> switch (f.mState) f.onAttach || f.performCreateView || f.performResume -> Fragment.performResume -> onResume() 从而,当Activity执行完生命周期后,就通过for循环执行了对应的所有Fragment的生命周期。
LifecycleOwner 1 2 3 4 5 6 7 // ComponentActivity中: private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this); public LifecycleRegistry(@NonNull LifecycleOwner provider) { mLifecycleOwner = new WeakReference<>(provider); mState = INITIALIZED; }
所以,谁创建了LifecycleRegistry,谁就是LifecycleOwner,或者说,谁创建LifecycleRegistry,谁就是被观察者,或者说LifecycleOwner就是ComponentActivity,就是被观察者。同时用了弱引用WeakReference,防止内存泄漏。如果不用弱引用,LifecycleRegistry持有Activity,如果LifecycleRegistry不释放,Activity就不释放,虽然activity走了onDestory。弱引用WeakReference当GC的时候就主动回收了。不用担心内存泄漏问题。
Lifecycle状态机 Lifecycle是LifecycleRegistry的父类。LifecycleRegistry不仅保存观察者map和被观察者owner,同时保存了状态机,和Event。这里的Event和生命周期是一一对应的。但是States跟Event不是一一对应的。
1 2 3 4 5 6 7 8 9 10 11 12 13 private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap = new FastSafeIterableMap<>();//观察者 /** * Current state */ private State mState;//状态机 /** * The provider that owns this Lifecycle. * Only WeakReference on LifecycleOwner is kept, so if somebody leaks Lifecycle, they won't leak * the whole Fragment / Activity. However, to leak Lifecycle object isn't great idea neither, * because it keeps strong references on all other listeners, so you'll leak all of them as * well. */ private final WeakReference<LifecycleOwner> mLifecycleOwner;//被观察者
所以这个图对应下边的代码,并且注意,这个states跟生命周期是没有关系的,是lifecycle独有的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 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); }
activity能直接用,是因为默认就支持了,在ComponentActivity父类中支持初始化了。 那其他可以用吗?可以。可以定义一个类实现LifecycleOwner接口,这个类里能拿到LifecycleRegistry,当其他组件执行生命周期是就调用LifecycleRegistry的分发机制就可以了。
参考资料 哔哩哔哩视频、源码版本是android-28
Ursprünglicher Link: http://nunu03.github.io/2022/06/02/LiveData-LifeCycle原理/
Copyright-Erklärung: 转载请注明出处.