LiveData常用方法源码分析

1、postValue
protected void postValue(T value) {
        boolean postTask;
        // 同步锁
        synchronized (mDataLock) {
            // 判断mPendingData是否为NOT_SET
            postTask = mPendingData == NOT_SET;
            // 对mPendingData赋值
            mPendingData = value;
        }
        // 防止数据重复设置
        if (!postTask) {
            return;
        }
        // 将数据发送到主线程处理
        ArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable);
    }

步骤分解:

  • 1、LiveData通过postValue方法在子线程同步方法中设置数据
  • 2、数据NOT_SET校验
  • 3、将数据发送到主线程进行处理
2、setValue
 @MainThread
    protected void setValue(T value) {
        assertMainThread("setValue"); // 1
        mVersion++; // 2
        mData = value; // 3
        dispatchingValue(null); // 4
    }

步骤分解:

  • 1、主线程校验
  • 2、计数器自加
  • 3、为mData赋值
  • 4、分发数据(详见dispatchingValue)
3、assertMainThread 主线程校验
 static void assertMainThread(String methodName) {
        if (!ArchTaskExecutor.getInstance().isMainThread()) {
            throw new IllegalStateException("Cannot invoke " + methodName + " on a background"
                    + " thread");
        }
    }
4、dispatchingValue
   void dispatchingValue(@Nullable ObserverWrapper initiator) {
        // 1
        if (mDispatchingValue) {
            mDispatchInvalidated = true;
            return;
        }
        // 2
        mDispatchingValue = true;
        do {
            mDispatchInvalidated = false;
            // 3
            if (initiator != null) {
                considerNotify(initiator);
                initiator = null;
            } else {
            // 4
                for (Iterator<Map.Entry<Observer<? super T>, ObserverWrapper>> iterator =
                        mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
                    considerNotify(iterator.next().getValue());
                    if (mDispatchInvalidated) {
                        break;
                    }
                }
            }
        } while (mDispatchInvalidated);
        mDispatchingValue = false;
    }

步骤分解:

  • 1、分发状态标记,防止重复分发
  • 2、修改分发状态
  • 3、分发通过参数传递进来的迭代器中数据
  • 4、将数据分发给所有观察者
5、considerNotify
 private void considerNotify(ObserverWrapper observer) {
        // 1
        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.
        
        // 2
        if (!observer.shouldBeActive()) {
            observer.activeStateChanged(false);
            return;
        }
        // 3
        if (observer.mLastVersion >= mVersion) {
            return;
        }
        // 4
        observer.mLastVersion = mVersion;
        // 5
        observer.mObserver.onChanged((T) mData);
    }

步骤分解

  • 1、观察者非active状态,拦截
  • 2、通过shouldBeActive修改观察者active状态
  • 3、version计数器比对
  • 4、调用onChange方法,分发数据
6、observe
  @MainThread
    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
        assertMainThread("observe");
        // 1
        if (owner.getLifecycle().getCurrentState() == DESTROYED) {
            // ignore
            return;
        }
        // 2
        LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
        // 3
        ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);
        // 4
        if (existing != null && !existing.isAttachedTo(owner)) {
            throw new IllegalArgumentException("Cannot add the same observer"
                    + " with different lifecycles");
        }
        if (existing != null) {
            return;
        }
        // 5
        owner.getLifecycle().addObserver(wrapper);
    }

步骤分解

  • 1、如果owner为DESTROYED状态,直接return
  • 2、构造LifecycleBoundObserver
  • 3、构造ObserverWrapper(详见putIfAbsent)
  • 4、对已经存在观察者抛出异常,防止重复添加监听
  • 5、添加合法观察者
7、putIfAbsent
  public V putIfAbsent(@NonNull K key, @NonNull V v) {
        Entry<K, V> entry = get(key);
        if (entry != null) {
            return entry.mValue;
        }
        put(key, v);
        return null;
    }
  • Entry形式存储K、V值,K不允许重复
8、map
 public static <X, Y> LiveData<Y> map(
            @NonNull LiveData<X> source,
            @NonNull final Function<X, Y> mapFunction) {
            // 1
        final MediatorLiveData<Y> result = new MediatorLiveData<>();
        // 2
        result.addSource(source, new Observer<X>() {
            @Override
            public void onChanged(@Nullable X x) {
                // 3
                result.setValue(mapFunction.apply(x));
            }
        });
        // 4
        return result;
    }

步骤分解

  • 1、创建MediatorLiveData
  • 2、通过addSource将源数据添加到result中
  • 3、为result添加源数据监听,并在接收到监听后setValue
  • 4、返回MediatorLiveData类型数据作为result
9、switchMap
 @MainThread
    @NonNull
    public static <X, Y> LiveData<Y> switchMap(
            @NonNull LiveData<X> source,
            @NonNull final Function<X, LiveData<Y>> switchMapFunction) {
            // 1
        final MediatorLiveData<Y> result = new MediatorLiveData<>();
        // 2
        result.addSource(source, new Observer<X>() {
            LiveData<Y> mSource;

            @Override
            public void onChanged(@Nullable X x) {
                // 3
                LiveData<Y> newLiveData = switchMapFunction.apply(x);
                // 4
                if (mSource == newLiveData) {
                    return;
                }
                // 5
                if (mSource != null) {
                    result.removeSource(mSource);
                }
                // 6
                mSource = newLiveData;
                // 7
                if (mSource != null) {
                    result.addSource(mSource, new Observer<Y>() {
                        @Override
                        public void onChanged(@Nullable Y y) {
                        // 8
                            result.setValue(y);
                        }
                    });
                }
            }
        });
        // 9
        return result;
    }

步骤分解

  • 1、创建MediatorLiveData类型result
  • 2、将源数据添加到result中
  • 3、通过switchMapFunction的apply函数创建LiveData类型数据newLiveData
  • 4、与前一次的数据相同,直接返回
  • 5、数据不为空,通过removeSource方法将数据从result中移除
  • 6、缓存newLiveData至mSource
  • 7、mSource不为空,将mSource作为源数据添加到result中
  • 8、为result添加源数据mSource监听,并在接收到监听后setValue
  • 9、返回MediatorLiveData类型数据result
10、addSource
 @MainThread
    public <S> void addSource(@NonNull LiveData<S> source, @NonNull Observer<? super S> onChanged) {
        // 1
        Source<S> e = new Source<>(source, onChanged);
        // 2
        Source<?> existing = mSources.putIfAbsent(source, e);
        // 3
        if (existing != null && existing.mObserver != onChanged) {
            throw new IllegalArgumentException(
                    "This source was already added with the different observer");
        }
        // 4
        if (existing != null) {
            return;
        }
        // 5
        if (hasActiveObservers()) {
            e.plug(); // 6
        }
    }

步骤分解

  • 1、以source和onChanged构造Source类型数据e
  • 2、以源数据source和e构造新的Source类型数据existing
  • 3、如果existing数据存在,也就是说之前已经为source添加过观察者情况,抛异常
  • 4、重复判断existing,进行返回
  • 5、如果有active的Observers,添加监听
  • 6、plug方法(详见plug)
11、plug() MediatorLiveData中
 void plug() {
            mLiveData.observeForever(this);
        }
  • observeForever
  /**
     * Adds the given observer to the observers list. This call is similar to
     * {@link LiveData#observe(LifecycleOwner, Observer)} with a LifecycleOwner, which
     * is always active. This means that the given observer will receive all events and will never
     * be automatically removed. You should manually call {@link #removeObserver(Observer)} to stop
     * observing this LiveData.
     * While LiveData has one of such observers, it will be considered
     * as active.
     * <p>
     * If the observer was already added with an owner to this LiveData, LiveData throws an
     * {@link IllegalArgumentException}.
     *
     * @param observer The observer that will receive the events
     */
  @MainThread
    public void observeForever(@NonNull Observer<? super T> observer) {
        assertMainThread("observeForever");
        // 1
        AlwaysActiveObserver wrapper = new AlwaysActiveObserver(observer);
        // 2
        ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);
        // 3
        if (existing instanceof LiveData.LifecycleBoundObserver) {
            throw new IllegalArgumentException("Cannot add the same observer"
                    + " with different lifecycles");
        }
        if (existing != null) {
            return;
        }
        // 4
        wrapper.activeStateChanged(true);
    }
  • 1、 通过observer构造AlwaysActiveObserver
  • 2、 通过observer和wrapper构造ObserverWrapper类型数据existing
  • 3、 如果existing数据已经存在,也就是说LiveData已经添加过该observer了,抛出异常
  • 4、修改wrapper的active状态为true
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值