LiveData

109 阅读1分钟

什么是LiveData:

LiveData是一个可观察的数据持有者,和常规的observable不同,LiveData是具有生命周期的感知能力。LiveData只会通知Active状态的观察者,处于onPause或者onDestory状态是不会收到通知的,需要注意的是,一旦观察者恢复Resumend状态,他将会重新收到LiveData的数据

LiveData提供了两种更新数据的方式

  • setValue(T value)
  • postValue(T value)

setValue()只能在主线程中调用,postValue()可以在任何线程中调用。

postValue()的执行 最终切换到主线程调用 setValue(T value)

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);    }};LiveData.observe 

@MainThreadpublic void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {    assertMainThread("observe");   //当前的状态如果是 DESTROYED 就直接不更新数据

    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);}