LiveData源码分析

使用

创建ViewModel

//继承ViewModel,创建LiveData
public class NameViewModel extends AndroidViewModel {

    private MutableLiveData<String> liveData;

    public MutableLiveData<String> getData() {
        if (liveData== null) {
            liveData= new MutableLiveData<String>();
        }
        return liveData;
    }

}

注册Observer

//注册观察者,监听LiveData数据变化
viewModel.getData().observe(this, new Observer<String>() {
    @Override
    public void onChanged(@Nullable String s) {
        mainFragmentText.setText(s);
    }
});

设置数据

//设置数据
if (viewModel.getData().getValue() != null && viewModel.getData().getValue().equals("world")) {
    viewModel.getData().setValue("hello");
} else {
    viewModel.getData().setValue("world");
}

源码分析

注册

viewModel.getData().observe(this, new Observer<String>() {
    @Override
    public void onChanged(@Nullable String s) {
        mainFragmentText.setText(s);
    }
});

进入observer

@MainThread
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
    //如果activity或fragment已经destroy了,则忽略
    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)) {
        //同一个observer,只有对应的 lifecycleOwner 不一样,才可以重新添加
        throw new IllegalArgumentException("Cannot add the same observer"
                + " with different lifecycles");
    }
    if (existing != null) {
        return;
    }
    //注册观察者,这种方式添加的observer,只有activity在active时才会收到数据更新的通知,此处不做具体阐述
    owner.getLifecycle().addObserver(wrapper);
}

进入LifecycleBoundObserver

LifeCycle-States

class LifecycleBoundObserver extends ObserverWrapper implements GenericLifecycleObserver {
    @NonNull final LifecycleOwner mOwner;

    LifecycleBoundObserver(@NonNull LifecycleOwner owner, Observer<T> observer) {
        super(observer);
        mOwner = owner;
    }

    @Override
    boolean shouldBeActive() {
        //onStart到onStop之间则认为是active状态
        return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);
    }

    @Override
    public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
        if (mOwner.getLifecycle().getCurrentState() == DESTROYED) {
            removeObserver(mObserver);
            return;
        }
        //刚刚生成LifecycleBoundObserver的实例时,shouldBeActive() == false
        activeStateChanged(shouldBeActive());
    }

    @Override
    boolean isAttachedTo(LifecycleOwner owner) {
        return mOwner == owner;
    }

    @Override
    void detachObserver() {
        mOwner.getLifecycle().removeObserver(this);
    }
}

进入ObserverWrapper

private abstract class ObserverWrapper {
    final Observer<T> mObserver;
    boolean mActive;
    int mLastVersion = START_VERSION;

    ObserverWrapper(Observer<T> observer) {
        mObserver = observer;
    }

    abstract boolean shouldBeActive();

    boolean isAttachedTo(LifecycleOwner owner) {
        return false;
    }

    void detachObserver() {
    }

    //注意区分observer的active状态和LiveData的active状态
    void activeStateChanged(boolean newActive) {
        if (newActive == mActive) {
            return;
        }
        // immediately set active state, so we'd never dispatch anything to inactive
        // owner
        mActive = newActive;
        //LiveData.this.mActiveCount表示处于active状态的observer的数量,当mActiveCount大于0时,LiveData处于active状态
        boolean wasInactive = LiveData.this.mActiveCount == 0;
        LiveData.this.mActiveCount += mActive ? 1 : -1;
        if (wasInactive && mActive) {
            //LiveData: inactive -> active
            onActive();
        }
        if (LiveData.this.mActiveCount == 0 && !mActive) {
            //LiveData: active -> inactive
            onInactive();
        }
        if (mActive) {//因为刚创建实例的时候mActive是false,所以此处不执行
            dispatchingValue(this);
        }
    }
}

发送

进入setValue

//setValue在主线程中工作,用于同步修改数据;postValue在后台线程中工作,用于异步修改数据
@MainThread
protected void setValue(T value) {
    assertMainThread("setValue");
    //每次更新value,都会使mVersion + 1,通过和ObserverWrapper的mLastVersion比较,避免重复通知客户
    mVersion++;
    mData = value;
    dispatchingValue(null);
}

进入dispatchingValue

private void dispatchingValue(@Nullable ObserverWrapper initiator) {
    if (mDispatchingValue) {//在observer回调中setValue会进入这里,将mDispatchInvalidated设置为true,可以让下面的循环知道数据被修改了,从而开始新的迭代
        mDispatchInvalidated = true;
        return;
    }
    mDispatchingValue = true;
    do {
        mDispatchInvalidated = false;
        if (initiator != null) {//如果initiator != null,表示仅通知initiator
            considerNotify(initiator);
            initiator = null;
        } else {//如果initiator == null,表示要通知所有的observer
            for (Iterator<Map.Entry<Observer<T>, ObserverWrapper>> iterator =
                    mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
                considerNotify(iterator.next().getValue());
                if (mDispatchInvalidated) {//如果在observer回调中调用了setValue,此处会break
                    break;
                }
            }
        }
    } while (mDispatchInvalidated);//如果在observer回调中调用了setValue,循环会重新开始
    mDispatchingValue = false;
}

进入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;
    }
    //对于LifecycleBoundObserver来说,即使LiveData的数据没有变化,只要activity的生命周期发生了改变,还是可能会调用considerNotify多次。这里通过比较observer.mLastVersion和mVersion,就能够知道observer是否已经拥有了最新的数据
    if (observer.mLastVersion >= mVersion) {
        return;
    }
    observer.mLastVersion = mVersion;
    //noinspection unchecked
    observer.mObserver.onChanged((T) mData);
}

进入onChanged

viewModel.getData().observe(this, new Observer<String>() {
    @Override
    public void onChanged(@Nullable String s) {
        mainFragmentText.setText(s);
    }
});

参考文章

添加新评论