AndroidX设计架构MVVM之LiveDatal生命周期及数据监听分析

AndroidX设计架构MVVM之LiveDatal2.1.0生命周期及数据监听分析

原文
AndroidX设计架构MVVM之ViewModel创建流程原理分析
AndroidX设计架构MVVM之ViewModel生命周期分析
AndroidX设计架构MVVM之LiveDatal生命周期及数据监听分析
AndroidX设计架构MVVM之DataBinding搭配LiveData的分析
AndroidX设计架构MVVM之DataBinding+ViewModel+LiveData

LiveData的简单使用,详细使用参考其他^^

//分析点1
 getViewModel().getUserInfo().observe(this, new Observer<UserBean>() {
            @Override
            public void onChanged(UserBean userBean) {
                Toast.makeText(MvvmMainActivity.this, userBean.getName(), Toast.LENGTH_SHORT).show();
            }
        });
 //分析点2
  getViewModel().getUserInfo().setValue(UserBean.UserBeanBuilder.newBuilder().setName("小明").setAge("11").build());

分析点1:主要有两部分1)对View生命周期进行监听,2)对LiveData数据进行监听

  @MainThread
    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
        assertMainThread("observe");
        //在destroy中直接返回
        if (owner.getLifecycle().getCurrentState() == DESTROYED) {
            // ignore
            return;
        }
        //分析点3
        LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
        //将包装的Observer保存在livedata的观察者列表中
        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;
        }
        //添加到view生命周期的观察者集合中
        owner.getLifecycle().addObserver(wrapper);
    }

先看分析点3:LifecycleBoundObserver实现了LifecycleEventObserver ,而LifecycleEventObserver 继承了LifecycleObserver,因此可以添加到View的生命周期的观察者列表中。

先看一下LifecycleBoundObserver的父类ObserverWrapper,它有通知当前监听者的功能 ,详情看注释

 private abstract class ObserverWrapper {
        final Observer<? super T> mObserver;
        boolean mActive;
        int mLastVersion = START_VERSION;

        ObserverWrapper(Observer<? super T> observer) {
           //这里是代码中new出来的的那个observer对象,从子类中传入的
            mObserver = observer;
        }

        abstract boolean shouldBeActive();

        boolean isAttachedTo(LifecycleOwner owner) {
            return false;
        }

        void detachObserver() {
        }
       
       //向当前的监听者进行通知 
        void activeStateChanged(boolean newActive) {
           //生命周期没有变化,直接返回,即没有出现【onStart,onPause】区间和
           //非【onStart,onPause】区间的切换
            if (newActive == mActive) {
                return;
            }
            // immediately set active state, so we'd never dispatch anything to inactive
            // owner
            mActive = newActive;
            //mActiveCount = 0时说明处于非
            boolean wasInactive = LiveData.this.mActiveCount == 0;
            LiveData.this.mActiveCount += mActive ? 1 : -1;
            if (wasInactive && mActive) {
               //生命周期状态在 started 或 resumed时,且是从非活动状态切换过来的
                onActive();
            }
            if (LiveData.this.mActiveCount == 0 && !mActive) {
                onInactive();
            }
            //mActive为true时,表示生命周期从Inactive转换到了active状态
            //这时要刷新数据
            if (mActive) {
                 // 分析点4 :向当前的监听者进行通知 
                dispatchingValue(this);
            }
        }
    }

而子类LifecycleBoundObserver 主要负责生命周期的判断以及传递

class LifecycleBoundObserver extends ObserverWrapper implements LifecycleEventObserver {
        @NonNull
        final LifecycleOwner mOwner;

        LifecycleBoundObserver(@NonNull LifecycleOwner owner, Observer<? super T> observer) {
            super(observer);
            mOwner = owner;
        }

        @Override
        boolean shouldBeActive() {
          //判断当前生命周期是否在【onStart,onPause】区间
            return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);
        }

        @Override
        public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
            if (mOwner.getLifecycle().getCurrentState() == DESTROYED) {
                removeObserver(mObserver);
                return;
            }
            //传递对生命周期的判断
            activeStateChanged(shouldBeActive());
        }

        @Override
        boolean isAttachedTo(LifecycleOwner owner) {
            return mOwner == owner;
        }

        @Override
        void detachObserver() {
            mOwner.getLifecycle().removeObserver(this);
        }
    }

接下来看分析点2:setValue()方法中对value的版本进行了记录mVersion,这个随后看。

 @MainThread
    protected void setValue(T value) {
        assertMainThread("setValue");
        //记录当前版本
        mVersion++;
        mData = value;
        dispatchingValue(null);
    }
   

那么分析点2和分析点4的区别就在于dispatchingValue()传值是否为null。

void dispatchingValue(@Nullable ObserverWrapper initiator) {
       //通知各个监听者中
        if (mDispatchingValue) {
            mDispatchInvalidated = true;
            return;
        }
        mDispatchingValue = true;
        do {
            mDispatchInvalidated = false;
            if (initiator != null) {
              //不为空,则只通知传入的监听者
                considerNotify(initiator);//分析点5
                initiator = null;
            } else {
                //则通知所有的监听者
                for (Iterator<Map.Entry<Observer<? super T>, ObserverWrapper>> iterator =
                        mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
                    //分析点5
                    considerNotify(iterator.next().getValue());
                    if (mDispatchInvalidated) {
                        break;
                    }
                }
            }
        } while (mDispatchInvalidated);
        mDispatchingValue = false;
    }

分析点5:到这一步才是真正的对观察者的通知

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;
        }
        //value 当前版本不大于上一次的,直接返回
        if (observer.mLastVersion >= mVersion) {
            return;
        }
        //更新上一次的value版本
        observer.mLastVersion = mVersion;
        //noinspection unchecked
        //onChanged 眼熟吧,就是在代码中创建observer的方法
        observer.mObserver.onChanged((T) mData);
    }

接下来简单分析一下postValue():其实就在利用Handler来切换到主线程的。

   protected void postValue(T value) {
        boolean postTask;
        synchronized (mDataLock) {
            postTask = mPendingData == NOT_SET;
            mPendingData = value;
        }
        if (!postTask) {
            return;
        }
        ArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable);
    }
    
 private final Runnable mPostValueRunnable = new Runnable() {
        @Override
        public void run() {
            Object newValue;
            synchronized (mDataLock) {
                newValue = mPendingData;
                mPendingData = NOT_SET;
            }
            //noinspection unchecked
            setValue((T) newValue);
        }
    };

总结:
1)livedata的observe(),将传入的LifecycleOwner和Observer封装为LifecycleBoundObserver对象,并保存到LiveData的观察者集合中,同时加入到View的生命周期观察者集合中。
2)(参考分析点3)当生命周期由InActive状态切换到Active状态时会通知当前的LiveData的观察者,这个主要用于在InActive状态时数据发生变化时进行刷新。
3)而使用setValue()时,将通知LiveData所有观察者。

点赞