01LiveData基础之基本用法附带demo
02Lifecycle-LiveData基础之自定义livedata附带demo
03Lifecycle-LiveData基础之map使用附带demo
04Lifecycle-LiveData基础之配合room 或者配合协程使用附带demo
介绍 及官方文档
LiveData
是一种可观察的数据存储器类。与常规的可观察类不同,LiveData 具有生命周期感知能力,意指它遵循其他应用组件(如 Activity、Fragment 或 Service)的生命周期。这种感知能力可确保 LiveData 仅更新处于活跃生命周期状态的应用组件观察者。
个人理解:livedata 专注于数据 可以通过observe()监听数据的变化(不限于基本的数据类型 对象也可以)
1.导入
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.2.0"
具体最新版本可以去官网查
2.基本用法
//创建一个key值 "string"为默认值
val key = MutableLiveData("string")
//获取 值
key.getValue()
//key值更改为 "新值" 官方 建议setValue 只在主线程使用
key.setValue("新值")
//key值更改为 "postValue 值" 官方 建议不在主线程时 要使用 postValue 更改值
key.postValue("postValue 值")
//给key 增加监听 当key中的值改变时 则会走回调 observe() 第一个参数 LifecycleOwner 传入 activity/Fragment/Service
//LifecycleOwner不在本章节讨论 可以看Lifecyc(具体就是标记了各个生命周期)
key.observe(this@MainActivity,
Observer<String> { Toast.makeText(this@MainActivity, it, Toast.LENGTH_LONG).show()})
3.setValue()和postValue的区别
干了这碗源码
protected void postValue(T value) {
boolean postTask;
synchronized (mDataLock) {
postTask = mPendingData == NOT_SET;
mPendingData = value;
}
if (!postTask) {
return;
}
ArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable);
}
@MainThread
protected void setValue(T value) {
assertMainThread("setValue");
mVersion++;
mData = value;
dispatchingValue(null);
}
//可以看到 postvalue 增加 synchronized 线程安全 postvalue 饶了一圈 最后还是调用了 setValue
//我在测试的时候 setValue 在子线程调用 会抛出异常 Cannot invoke setValue on a background thread
4.observe 添加订阅(数据监听器)
//ComponentActivity 和 fragment 都实现了这个接口
public interface LifecycleOwner {
/**
* Returns the Lifecycle of the provider.
*
* @return The lifecycle of the provider.
*/
@NonNull
Lifecycle getLifecycle();
}
//这个是LiveData的订阅部分源码
//可以看到 owner.getLifecycle().getCurrentState() == DESTROYED 就return了
//DESTROYED 基本标记生命周期销毁了
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);
}
代码:
Demo01