LiveData&Room:实时更新UI

2019-03-04  本文已影响1人  shiyuzhe

LiveData 是一个可以被观察的数据持有类
Room的query注解可以在数据库更新时更新LiveData

可被观察的数据持有类?

数据属于被观察者,当数据改变时通知给观察者(activity/fragment),当观察者处于活跃状态时更新UI,避免异步数据更新导致的内存泄漏等问题。

注册观察

只分析主线程:

 @MainThread
protected void setValue(T value) {
    assertMainThread("setValue");
    mVersion++;//version升级,通知被观察者的标识。
    mData = value;
    dispatchingValue(null);
}

//找到观察者,调用considerNotify(initiator)方法
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;
}
//在观察者活跃状态时判断version,有新数据时更新版本并通知观察者
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;
    //noinspection unchecked
    observer.mObserver.onChanged((T) mData);

LiveData总述

Room实现实时更新

When performing queries, you'll often want your app's UI to update automatically when the data changes. To achieve this, use a return value of type LiveData in your query method description. Room generates all necessary code to update theLiveData when the database is updated.

执行查询时,您通常希望应用程序的UI在数据更改时自动更新。 要实现此目的,请使用LiveData类型作为查询方法的返回类型。 Room会自动生成更新数据库时更新LiveData的代码。

Room provides the following support for return values of RxJava2 types:

上一篇 下一篇

猜你喜欢

热点阅读