• Android ViewModel,LiveData 简要分析


    ViewModel:

    负责为关联UI(activity/fragment)进行数据管理,业务逻辑处理。不直接持有view引用,不对UI进行访问调用操作

    对外通过暴露Livedata方式响应处理结果

    LiveData:

    可感知组件生命周期、被观察的数据源,在数据发生改变时进行通知提醒

    ViewModel处理数据后使用LiveData通知到observer数据已变更,

    Lifecycle:
    对象or组件生命周期状态定义接口,实现子类LifecycleRegistry。包含LifeCycleOwer和LifecycleObserver,分别是生命周期所有者和生命周期感知者

    Lifecycle定义组件状态

     

     ViewModel创建存储流程:

    组件与Livedata,Observer,Lifecycle关联流程:

     Livedata observe()

    @MainThread
        public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {//已销毁组件不作处理
            if (owner.getLifecycle().getCurrentState() == DESTROYED) {
                // ignore
                return;
            }
    //包装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;
            }
    //添加到Lifecyvle内保存
            owner.getLifecycle().addObserver(wrapper);
        }
    

    LiveData 添加LifecycleBoundObserver到LifecycleRegister内处理:

    public class LifecycleRegistry extends Lifecycle {
    
    @Override
    public void addObserver(LifecycleObserver observer) {
            State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
    //通过ObserverWithState包装LifecycleObserver内部进行操作管理
    ObserverWithState statefulObserver = new ObserverWithState(observer, initialState); 
    ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
     ...... 
    } 
    ......
    

     ObserverWithState负责分发组件状态变化,与关联的LifecycleBoundObserver状态关联

     static class ObserverWithState {
            State mState;
            GenericLifecycleObserver mLifecycleObserver;
    
            ObserverWithState(LifecycleObserver observer, State initialState) {
                mLifecycleObserver = Lifecycling.getCallback(observer);
                mState = initialState;
            }
    //分发组件状态到所关联Observer
            void dispatchEvent(LifecycleOwner owner, Event event) {
                State newState = getStateAfter(event);
                mState = min(mState, newState);
                mLifecycleObserver.onStateChanged(owner, event);
                mState = newState;
            }
        }
    

    看一下 LifecycleBoundObserver内部代码

    class LifecycleBoundObserver extends ObserverWrapper implements GenericLifecycleObserver {
            @NonNull final LifecycleOwner mOwner;
    
            LifecycleBoundObserver(@NonNull LifecycleOwner owner, Observer<T> observer) {
                super(observer);
                mOwner = owner;
            }
    ......
    //当组件周期状态变化时,处理关联的Observer @Override public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) { if (mOwner.getLifecycle().getCurrentState() == DESTROYED) { removeObserver(mObserver); return; } activeStateChanged(shouldBeActive()); } ...... } private abstract class ObserverWrapper { final Observer<T> mObserver; boolean mActive; int mLastVersion = START_VERSION; ObserverWrapper(Observer<T> observer) { mObserver = observer; } ...... void activeStateChanged(boolean newActive) {//组件周期变化时判断是否需要重新分发value data if (newActive == mActive) {//observe与组件状态一致时不处理, return; } // immediately set active state, so we'd never dispatch anything to inactive // owner mActive = newActive; boolean wasInactive = LiveData.this.mActiveCount == 0; LiveData.this.mActiveCount += mActive ? 1 : -1; if (wasInactive && mActive) {//LiveData从非活跃到激活状态 onActive(); } if (LiveData.this.mActiveCount == 0 && !mActive) {//LiveData从激活到非活跃状态 onInactive(); } if (mActive) {//组件激活状态时重新分发上一次存留数据 dispatchingValue(this); } } }

    LifeData分发数据处理:

    setValue修改数据

    @MainThread
        protected void setValue(T value) {
            assertMainThread("setValue");//主线程调用
            mVersion++;//每次修改,版本号+1
            mData = value;
            dispatchingValue(null);//数据分发处理
        }
    
     private void dispatchingValue(@Nullable ObserverWrapper initiator) {
            if (mDispatchingValue) {
                mDispatchInvalidated = true;
                return;
            }
            mDispatchingValue = true;
            do {
                mDispatchInvalidated = false;
                if (initiator != null) {//分发给指定observer
                    considerNotify(initiator);
                    initiator = null;
                } else {//分发Observer列表内所有注册对象
                    for (Iterator<Map.Entry<Observer<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;
            }
         
            // 是否为active状态
            if (!observer.shouldBeActive()) {
                observer.activeStateChanged(false);
                return;
            }//observer dataVersion大于等于LiveData dataVersion不予处理
            if (observer.mLastVersion >= mVersion) {
                return;
            }
            observer.mLastVersion = mVersion;
            //通知Observer change数据
            observer.mObserver.onChanged((T) mData);
        }
    

     整体大致流程:

  • 相关阅读:
    逆向实战干货,植物大战僵尸快速定位自动捡阳光Call,或者标志
    常见注入手法第二讲,APC注入
    Polipo
    Tinyproxy
    Varnish Cache
    jxls-1.x导出excel入门——基本操作
    【Hutool】Hutool工具类之日期时间工具——DateUtil
    SVN-Tips
    Java使用POI导出excel(下)——实例与小技巧
    Linux入门进阶第三天——软件安装管理(下)
  • 原文地址:https://www.cnblogs.com/happyxiaoyu02/p/9890443.html
Copyright © 2020-2023  润新知