玩转android.arch之LiveData
前一篇博文讲到android lifecycle, lifecycle包中还有一个livedata和viewModel.
- LiveData
其实liveData非常简单,作为一个数据持有类,提供数据和lifecycle给观察者,用rx的话说就是一个Observable,可以在lifecycle允许的范围内将数据提供给observer.
先看个最简单的例子
LiveData<Integer> observable = new LiveData<Lifecycle.Event>(){
@Override
protected void onInactive() {
super.onInactive();
setValue(1);;
Log.i(TAG, "onDestroy444: " + Thread.currentThread().getName());
}
@Override
protected void onActive() {
super.onActive();
setValue(0);
}
} ;
observable.observe(this, event1 -> Log.i(TAG, "setLifCycle: " + event1));
此例子中当Livedata中lifecycle发生变化时发送不同的数字出来,此为非常简单的例子。正常使用时应该在onActive开始请求数据,在onInactive时结束请求数据,在此期间使用setvalue()将数据设置进来,对应的observer就会收到变化的数据。简单使用就这么简单,下边讲一下需要注意的地方。
再看LiveData源码,仅贴上最重要的4个方法部分源码
public abstract class LiveData<T> {
protected void onActive() {
}
protected void onInactive() {
}
@MainThread
protected void setValue(T value) {
assertMainThread("setValue");
mVersion++;
mData = value;
dispatchingValue(null);
}
protected void postValue(T value) {
boolean postTask;
synchronized (mDataLock) {
postTask = mPendingData == NOT_SET;
mPendingData = value;
}
if (!postTask) {
return;
}
AppToolkitTaskExecutor.getInstance().postToMainThread(mPostValueRunnable);
}
@MainThread
public void observe(LifecycleOwner owner, Observer<T> observer) {
if (owner.getLifecycle().getCurrentState() == DESTROYED) {
// ignore
return;
}
LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
LifecycleBoundObserver existing = mObservers.putIfAbsent(observer, wrapper);
if (existing != null && existing.owner != wrapper.owner) {
throw new IllegalArgumentException("Cannot add the same observer"
+ " with different lifecycles");
}
if (existing != null) {
return;
}
owner.getLifecycle().addObserver(wrapper);
wrapper.activeStateChanged(isActiveState(owner.getLifecycle().getCurrentState()));
}
}
onActive
为当观察者数从0到1时调用,onInactive
当观察者数从1变为0时调用,当绑定的lifecycleOwer生命周期ondestroy时,会自动移除livedata上的所有观察者。所以如果是在onInActivte调用setvalue,observer是无法收到事件的,因为已经将observer移除了。
实际上onInactive
限制了Lifecycle 处于 STARTED 或 RESUMED 状态时才能发送数据。
在void observe(LifecycleOwner owner, Observer<T> observer)
和protected void setValue(T value)
上都标有@MainThread
标注,说明必须在mainthread调用,如果在其他线程请调用postValue(T value)
实际上LiveData还可以用于fragment间通讯。典型的如listfragment和detaileFragment。
LiveData就这么简单。