LiveData核心源码解析

2021/9/14 17:06:20

本文主要是介绍LiveData核心源码解析,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1、setValue()

在主线程调用用于为LiveData设置数据,同时向活跃的observers发送状态变更通知

  /**
     * Sets the value. If there are active observers, the value will be dispatched to them.
     * <p>
     * This method must be called from the main thread. If you need set a value from a background
     * thread, you can use {@link #postValue(Object)}
     *
     * @param value The new value
     */
    @MainThread
    protected void setValue(T value) {
        // 1 线程检测
        assertMainThread("setValue");
        // 添加数据版本,方便后面更新数据用
        mVersion++;
        // 对数据进行赋值
        mData = value;
        // 2 分发数据
        dispatchingValue(null);
    }
1.1 LiveData assertMainThread

线程判断,判断方法是否在主线程中执行,非主线程,抛出异常

    static void assertMainThread(String methodName) {
        if (!ArchTaskExecutor.getInstance().isMainThread()) {
            throw new IllegalStateException("Cannot invoke " + methodName + " on a background"
                    + " thread");
        }
    }    
  • ArchTaskExecutor中isMainThread()

通过delegate类进行线程判断

 @Override
    public boolean isMainThread() {
        return mDelegate.isMainThread();
    }
  • 默认构造方法使用DefaultTaskExecutor为mDelegate赋值
private ArchTaskExecutor() {
        mDefaultTaskExecutor = new DefaultTaskExecutor();
        mDelegate = mDefaultTaskExecutor;
    }
  • DefaultTaskExecutor中isMainThread()

通过Looper判断当前线程looper是否为主线程looper

  @Override
    public boolean isMainThread() {
        return Looper.getMainLooper().getThread() == Thread.currentThread();
    }
1.2 LiveData dispatchingValue

分发数据

  @SuppressWarnings("WeakerAccess") /* synthetic access */
    void dispatchingValue(@Nullable ObserverWrapper initiator) {
        // 分发标记,防止重复通知
        if (mDispatchingValue) {
            // 刷新标记
            mDispatchInvalidated = true;
            return;
        }
        // 修改分发标记为true
        mDispatchingValue = true;
        do {
            // 修改刷新标记为false
            mDispatchInvalidated = false;
            if (initiator != null) {
                // 使用外部initiator
                considerNotify(initiator);
                // 将initiator置空
                initiator = null;
            } else {
                // 迭代mObservers
                for (Iterator<Map.Entry<Observer<? super T>, ObserverWrapper>> iterator =
                        mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
                    // 分发数据    
                    considerNotify(iterator.next().getValue());
                    // 退出迭代器
                    if (mDispatchInvalidated) {
                        break;
                    }
                }
            }
            // 保证执行一次
        } while (mDispatchInvalidated);
        mDispatchingValue = false;
    }
  • LiveData中considerNotify()
   private void considerNotify(ObserverWrapper observer) {
        // active状态检查
        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.
        // 修改 observer状态
        if (!observer.shouldBeActive()) {
            observer.activeStateChanged(false);
            return;
        }
        // version检查
        if (observer.mLastVersion >= mVersion) {
            return;
        }
        // 修改LastVersion值
        observer.mLastVersion = mVersion;
        // 调用onChange通知数据变更
        observer.mObserver.onChanged((T) mData);
    }
2、LiveData 中postValue
   protected void postValue(T value) {
        boolean postTask;
        // 同步锁,保证多线程数据安全
        synchronized (mDataLock) {
        // 默认mPendingData为NOT_SET状态,post为true
            postTask = mPendingData == NOT_SET;
            // 赋值
            mPendingData = value;
        }
        // 未设定值,return
        if (!postTask) {
            return;
        }
        //  1 发送一个任务到主线程执行
        ArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable);
    }
  • 2.1 LiveData中mPostValueRunnable
  private final Runnable mPostValueRunnable = new Runnable() {
        @SuppressWarnings("unchecked")
        @Override
        public void run() {
            Object newValue;
            synchronized (mDataLock) {
                // 将mPendingData赋值给newValue
                newValue = mPendingData;
                // 复位mPendingData值为NOT_SET
                mPendingData = NOT_SET;
            }
            // 调用主线程setValue
            setValue((T) newValue);
        }
    };
  • 通过设置对象锁保证多次调用postValue时只改变mPendingData,不会重复调用setValue方法,防止重复发通知问题。
  • 当setValue和postValue通知执行时,postValue修改的值会覆盖setValue修改的值。
  • 2.2 ArchTaskExecutor 中postToMainThread()
 @Override
    public void postToMainThread(Runnable runnable) {
        mDelegate.postToMainThread(runnable);
    }
  • DefaultTaskExecutor中postToMainThread
   @Override
    public void postToMainThread(Runnable runnable) {
        // doubleCheck 单例创建mHandler
        if (mMainHandler == null) {
            synchronized (mLock) {
                if (mMainHandler == null) {
                    mMainHandler = createAsync(Looper.getMainLooper());
                }
            }
        }
        // 通过handler发送到主线程
        mMainHandler.post(runnable);
    }
  • DefaultTaskExecutor中createAsync
    根据SDK版本创建handler
  private static Handler createAsync(@NonNull Looper looper) {
        if (Build.VERSION.SDK_INT >= 28) {
            // 不会阻塞线程
            return Handler.createAsync(looper);
        }
        if (Build.VERSION.SDK_INT >= 16) {
            try {
                return Handler.class.getDeclaredConstructor(Looper.class, Handler.Callback.class,
                        boolean.class)
                        .newInstance(looper, null, true);
            } catch (IllegalAccessException ignored) {
            } catch (InstantiationException ignored) {
            } catch (NoSuchMethodException ignored) {
            } catch (InvocationTargetException e) {
                return new Handler(looper);
            }
        }
        return new Handler(looper);
    }
3、LiveData中observe()方法

1、将观察者添加到observers list中,存活的生命周期与其owner(Activity或者Fragment)相同
2、监听事件在主线程中进行分发,如果LiveData数据发生变更,将会通知observer
3、observer只有在Lifecycle.State处于STARTED或者RESUMED状态时,才会收到通知
4、owner状态变更为Lifecycle.State的DESTROYED状态时,observer将会被自动移除
5、当owner不处于active状态时,observer不会接收到数据变更,但是当状态重新恢复到active状态时,会自动收到最近可用数据
6、LiveData在owner中observer处于active时,保持对observer的强引用,当owner处于destory状态时,会自动移除引用
7、如果owner已经处于destory状态时,LiveData会忽略状态变更请求
8、如果owner设置的observer已经处于observers中,会忽略新的observer添加操作
9、如果observers中的observer已经拥有另外的一个owner,LiveData会抛出IllegalArgumentException

  @MainThread
    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
    // 主线程断言
        assertMainThread("observe");
        // 忽略destory状态
        if (owner.getLifecycle().getCurrentState() == DESTROYED) {
            // ignore
            return;
        }
        //  1 将owner与observer作为参数创建LifecycleBoundObserver
        LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
        //  1 查询mObservers中是否包含间为observer的值,存在返回键对应的值,不存在存储并返回null
        ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);
        // owner 重复判断
        if (existing != null && !existing.isAttachedTo(owner)) {
            throw new IllegalArgumentException("Cannot add the same observer"
                    + " with different lifecycles");
        }
        // 已经存在返回,防止重复添加
        if (existing != null) {
            return;
        }
        //  3 将wrapper添加到关联的owner的lifeCycle中关联生命周期
        owner.getLifecycle().addObserver(wrapper);
    }
3.1 LiveData中LifecycleBoundObserver
 class LifecycleBoundObserver extends ObserverWrapper implements LifecycleEventObserver {
        @NonNull
        final LifecycleOwner mOwner;

        LifecycleBoundObserver(@NonNull LifecycleOwner owner, Observer<? super T> observer) {
            super(observer);
            mOwner = owner;
        }
        
        // active状态判断
        @Override
        boolean shouldBeActive() {
            return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);
        }

        @Override
        public void onStateChanged(@NonNull LifecycleOwner source,
                @NonNull Lifecycle.Event event) {
                // mOwner状态变更为DESTORY时移除观察者
            if (mOwner.getLifecycle().getCurrentState() == DESTROYED) {
                removeObserver(mObserver);
                return;
            }
            // 发出状态变更通知
            activeStateChanged(shouldBeActive());
        }

        @Override
        boolean isAttachedTo(LifecycleOwner owner) {
            return mOwner == owner;
        }
        
        // 移除observer
        @Override
        void detachObserver() {
            mOwner.getLifecycle().removeObserver(this);
        }
    }
  • 3.1.1 LiveData中ObserverWrapper中activeStateChanged()方法
  void activeStateChanged(boolean newActive) {
            // 状态相同不处理
            if (newActive == mActive) {
                return;
            }
            // immediately set active state, so we'd never dispatch anything to inactive
            // owner  将newActive值赋给mActive
            mActive = newActive;
            // 根据mActiveCount判断LiveData是否为active状态
            boolean wasInactive = LiveData.this.mActiveCount == 0;
            // mAvtive为true时,mActiveCount加1,false时减1
            LiveData.this.mActiveCount += mActive ? 1 : -1;
            // mActiveCount为0并且mActive为true时,调用onActive处于激活状态
            if (wasInactive && mActive) {
                onActive();
            }
            // mActive1为false,调用onInactive处于非active状态
            if (LiveData.this.mActiveCount == 0 && !mActive) {
                onInactive();
            }
            // 分发数据
            if (mActive) {
                dispatchingValue(this);
            }
        }
3.2 SafeIterableMap中putIfAbsent
   public V putIfAbsent(@NonNull K key, @NonNull V v) {
        // 通过key查询entry
        Entry<K, V> entry = get(key);
        // entry 不为空,直接返回entry的mValue
        if (entry != null) {
            return entry.mValue;
        }
        // 为空存储key,v
        put(key, v);
        // 返回null
        return null;
    }
3.3 owner.getLifecycle().addObserver(wrapper)
  • 源码追溯到LifecycleRegistry中addObserver,实现LiveData与owner生命周期的绑定。
   @Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        //  使用observer和initialState作为参数构建statefulObserver
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);

        if (previous != null) {
            return;
        }
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
        if (lifecycleOwner == null) {
            // it is null we should be destroyed. Fallback quickly
            return;
        }

        boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
        //  计算状态值
        State targetState = calculateTargetState(observer);
        mAddingObserverCounter++;
        while ((statefulObserver.mState.compareTo(targetState) < 0
                && mObserverMap.contains(observer))) {
                //  将statefulObserver的state值添加到ParentState中
            pushParentState(statefulObserver.mState);
            // 将更新后的状态及lifecycleOwner交给statefulObserver进行分发
            statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
            // 移除ParentState中最后一个元素
            popParentState();
            // mState / subling may have been changed recalculate
            // 重新计算observer状态
            targetState = calculateTargetState(observer);
        }
        
        // 不允许重入状态
        if (!isReentrance) {
            // we do sync only on the top level.
            // 同步执行
            sync();
        }
        // 正在添加的observer数量减1
        mAddingObserverCounter--;
    }
4、Transformations.map()方法
  @MainThread
    @NonNull
    public static <X, Y> LiveData<Y> map(
            @NonNull LiveData<X> source,
            @NonNull final Function<X, Y> mapFunction) {
            // 构建MediatorLiveData类型result
        final MediatorLiveData<Y> result = new MediatorLiveData<>();
        //  1 将source作为源数据进行处理
        result.addSource(source, new Observer<X>() {
            @Override
            public void onChanged(@Nullable X x) {
                // 通过mapFunction.apply方法将数据转换,数据变更后调用result的setValue,发送数据变更通知观察者
                result.setValue(mapFunction.apply(x));
            }
        });
        // 将结果返回
        return result;
    }

将传入的LiveData作为数据源,通过传入的指定函数操作后,将处理后的数据结果返回

4.1 MediatorLiveData中addSource()
   @MainThread
    public <S> void addSource(@NonNull LiveData<S> source, @NonNull Observer<? super S> onChanged) {
        // 构建Source
        Source<S> e = new Source<>(source, onChanged);
        // 添加到mSources中
        Source<?> existing = mSources.putIfAbsent(source, e);
        if (existing != null && existing.mObserver != onChanged) {
            throw new IllegalArgumentException(
                    "This source was already added with the different observer");
        }
        if (existing != null) {
            return;
        }
        if (hasActiveObservers()) {
            // 为数据注册观察者
            e.plug();
        }
    }
  • Source中plug方法
  void plug() {
            mLiveData.observeForever(this);
        }
  • Source中onChanged方法
 @Override
        public void onChanged(@Nullable V v) {
            if (mVersion != mLiveData.getVersion()) {
                mVersion = mLiveData.getVersion();
                mObserver.onChanged(v);
            }
        }

数据变更回调,接收到回调后通过mObserver.onChanged方法将数据变更通知发出

5、Transformations.switchMap
   @MainThread
    @NonNull
    public static <X, Y> LiveData<Y> switchMap(
            @NonNull LiveData<X> source,
            // 1
            @NonNull final Function<X, LiveData<Y>> switchMapFunction) {
        final MediatorLiveData<Y> result = new MediatorLiveData<>();
        result.addSource(source, new Observer<X>() {
            LiveData<Y> mSource;

            @Override
            public void onChanged(@Nullable X x) {
                // 将转换后的数据作为新的LiveData
                LiveData<Y> newLiveData = switchMapFunction.apply(x);
                if (mSource == newLiveData) {
                    return;
                }
                if (mSource != null) {
                    result.removeSource(mSource);
                }
                // 赋值给mSource
                mSource = newLiveData;
                if (mSource != null) {
                    result.addSource(mSource, new Observer<Y>() {
                        @Override
                        public void onChanged(@Nullable Y y) {
                            result.setValue(y);
                        }
                    });
                }
            }
        });
        return result;
    }

通过对比map方法,两个方法区别是Function方法第二个参数不同,返回值必须为一个LiveData类型数据。

6、流程图:

在这里插入图片描述



这篇关于LiveData核心源码解析的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程