美文网首页
LiveData解析

LiveData解析

作者: Zero_Wrold | 来源:发表于2019-10-17 11:23 被阅读0次

LiveData is a data holder class that can be observed within a given lifecycle.
LiveData 是一个可以在给定生命周期中,持有数据并可监听其变化的类

使用

class NameViewModel:ViewModel() {
     val nameLiveData by lazy { MutableLiveData<String>() }

}

先创建一个ViewModelViewModel中创建一个MutableLiveData

 nameViewModel.nameLiveData.observe(this, Observer<String> {
            tvName.text = it
        })

Activity 中给MutableLiveData注册一个观察者

  btn.setOnClickListener {
            nameViewModel.nameLiveData.value = "设置名字"
        }

在点击事件中给nameLiveDatavalue 赋值,这样就会执行ObserveronChanged的方法将tvNametext赋值
这样一个简单的LiveData的Demo就完成了

解析

首先我们看observe方法是怎样实现的

 @MainThread
    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
        assertMainThread("observe");
        if (owner.getLifecycle().getCurrentState() == DESTROYED) {
            // ignore
            return;
        }
        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;
        }
        owner.getLifecycle().addObserver(wrapper);
    }

observe方法需要传入两个参数,第一个是LifecycleOwner 由于AppcompatActivity本身就间接实现了这个接口,所以我们传入this,第二个参数是一个Observer

public interface Observer<T> {
    /**
     * Called when the data is changed.
     * @param t  The new data
     */
    void onChanged(T t);
}

这个用于数据改变的监听
继续往下看,当LifecycleOwner的状态为DESTROYED被销毁时,这个监听也就没有必要,直接return
LifecycleBoundObserver

class LifecycleBoundObserver extends ObserverWrapper implements LifecycleEventObserver {
  ...
}
public interface LifecycleEventObserver extends LifecycleObserver {
    /**
     * Called when a state transition event happens.
     *
     * @param source The source of the event
     * @param event The event
     */
    void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}

我们可以看到LifecycleBoundObserver 实现了LifecycleEventObserver,而LifecycleEventObserver,继承自LifecycleObserver,所以当生命周期发生改变时,会执行onStateChanged方法
我们看一下LifecycleBoundObserveronStateChanged方法实现

 @Override
        public void onStateChanged(@NonNull LifecycleOwner source,
                @NonNull Lifecycle.Event event) {
            if (mOwner.getLifecycle().getCurrentState() == DESTROYED) {
                removeObserver(mObserver);
                return;
            }
            activeStateChanged(shouldBeActive());
        }

首先判断了LifecycleOwner是否被销毁,如果销毁则移除Observer
然后执行了shouldBeActiveactiveStateChanged

@Override
        boolean shouldBeActive() {
            return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);
        }

shouldBeActive判断生命周期是否在STARTED

void activeStateChanged(boolean newActive) {
            if (newActive == mActive) {
                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) {
                onActive();
            }
            if (LiveData.this.mActiveCount == 0 && !mActive) {
                onInactive();
            }
            if (mActive) {
                dispatchingValue(this);
            }
        }

我么你可以看到onActive 会在mActiveCount 为 1 时触发,onInactive方法则只会在 mActiveCount 为 0 时触发
这两个方法都是空实现,当 mActive==true 时也就是说处于激活状态执行dispatchingValue

void dispatchingValue(@Nullable ObserverWrapper initiator) {
        if (mDispatchingValue) {
            mDispatchInvalidated = true;
            return;
        }
        mDispatchingValue = true;
        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;
    }

mDispatchingValue 这个变量用来控制,是否进入while 循环,以及while 循环 是否已经结束
mDispatchInvalidated 这个变量用来控制for 循环
我们看considerNotify方法

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;
        }
        if (observer.mLastVersion >= mVersion) {
            return;
        }
        observer.mLastVersion = mVersion;
        observer.mObserver.onChanged((T) mData);
    }

当前生命周期不时活跃状态不执行,如果数据没有发生变化不执行,
我们再看LiveDatasetValue方法

 @MainThread
    protected void setValue(T value) {
        assertMainThread("setValue");
        mVersion++;
        mData = value;
        dispatchingValue(null);
    }

直接执行了dispatchingValue方法且传入null就执行所有的ObserveronChanged

分析到此结束。

相关文章

  • LiveData解析

    1. 简介 长久以来我们都要去了解Activity或者Fragment的生命周期,因为界面的生命周期是我们处理数据...

  • LiveData解析

    LiveData is a data holder class that can be observed with...

  • 学习笔记LiveData

    学习下LiveData目录 如何使用 源码解析 粘性事件 1、使用 LiveData是Google的提供标准化开发...

  • Jetpack-LiveData源码解析

    LiveData源码解析 源码版本:2.4.0需会使用:Lifecycle 导航:Jetpack-Lifecycl...

  • ViewModel

    ViewModel生命周期 LiveData,ViewModel,Lifecycle原理解析以及使用 - 简书 (...

  • 从源码看 Jetpack(4)-LiveData衍生

    上篇文章介绍了关于 LiveData 类的源码解析,本篇文章再来介绍下 LiveData 的一系列衍生类及衍生方法...

  • LiveData源码解析

    LiveData 使用最新的 androidx 的源码。 前言 LiveData 是 Android Archit...

  • LiveData源码解析

    0.前言 关于livedata的使用详情见LiveData+ViewModel+RxJava2+autoDispo...

  • LiveData源码解析

    LiveData is a data holder class that can be observed with...

  • LiveData源码解析

    LiveData官方资料Lifecycle官方资料ViewModel官方资料 本文适合对Lifecycle、Liv...

网友评论

      本文标题:LiveData解析

      本文链接:https://www.haomeiwen.com/subject/falmmctx.html