参考:
LiveData 是一个可观察的数据持有者类,与常规 observable 不同,LiveData 是生命周期感知的
LiveData和lifecycle 有什么区别?
LiveData里面要传一个lifecycle对象
mutableLiveData.observe(this, new Observer<String>() {
@Override
public void onChanged(String s) {
mutableLiveData.setValue(s);
activityMainBinding.tvShow.setText(s);
}
});
源码分析:
public class MutableLiveData<T> extends LiveData<T> {
/**
* Creates a MutableLiveData initialized with the given {@code value}.
*
* @param value initial value
*/
public MutableLiveData(T value) {
super(value);
}
/**
* Creates a MutableLiveData with no value assigned to it.
*/
public MutableLiveData() {
super();
}
@Override
public void postValue(T value) {
super.postValue(value);
}
@Override
public void setValue(T value) {
super.setValue(value);
}
}
#### LiveData的优点
- 保持UI与数据的一致性:LiveData 遵循观察者设计模式,生命周期发生变化时,LiveData 会通知对应的应用程序组件(Observer),数据发生变化时也会通知更新 UI.
- 避免内存泄漏:这个 Observer 绑定了 Lifecycle 对象,当 Lifecycle 对象生命周期 destory 之后,这些 Observer 也会被自动清理。
- 避免 Activity 处于不活跃状态的时候产生崩溃:如果观察者(Observer)处于不活跃状态,则 Observer 不会接收任何 LiveData 事件。
- 不在手动处理生命周期:UI 组件只是观察相关数据,而不会停止或恢复观察,LiveData 会根据具体生命周期的变化而自动管理。
- 始终保持最新数据:如果生命周期为非活跃状态,则会在由非活跃状态转为活跃状态时接收最新数据,如从后台切换到前台自动接收最新数据。
- 正确处理配置更改:如果 Activity 或 Fragment 因为设备配置发生变化而重新创建,比如屏幕旋转等,也将会立即重新接收最新数据。
- 共享服务:可以借助 LiveData 数据的观察能力,根据 Livecycle 的生命周期状态随时连接或断开服务。
控件要监听控制
那么每一个控件都要写一次观察监听?、
LiceData 使用方式总结:
class PengViewModel extends ViewModel {
private MutableLiveData<String> data;
public MutableLiveData<String> getData() {
if(data==null){
data=new MutableLiveData<>();
data.postValue("peng");
}
return data;
}
}
pengViewModel= ViewModelProviders.of(this).get(PengViewModel.class);
MutableLiveData<String> mutableLiveData=pengViewModel.getData();
mutableLiveData.observe(this, new Observer<String>() {
@Override
public void onChanged(String s) {
mutableLiveData.setValue(s);
activityMainBinding.tvShow.setText(s);
}
});
使用总结:
1.在PengViewModel里面把viewModel和LiveData绑定
2.databing绑定viewmodel:一定是xml中定义了的viewmodel,会有跳转提示
activityMainBinding.setData(pengViewModel);
<data>
<variable
name="data"
type="com.example.myapplication.MyAndroidViewModel" />
</data>
MutableLiveData<String> mLiveData = mTestViewModel.getLiveData();
mLiveData.observe(this, new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
//更新UI
}
});
public class MViewModel extends ViewModel {
private MutableLiveData<String> data;
public LiveData<String> getData(){
if (data == null){
data = new MutableLiveData<>();
data.postValue(DataUtil.getData());
}
return data;
}
}
- 使用 LiveData 对象的 observe 或 observeForever 方法将对应的 Activity 或 Fragment 等添加为该 LiveData 对象的观察者,如下:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this,R.layout.activity_main);
MViewModel mViewModel = ViewModelProviders.of(this).get(MViewModel.class);
mViewModel.getData().observe(this, new Observer<String>() {
@Override
public void onChanged(String msg) {
binding.setData(msg);
}
});
}
- 使用 LiveData 的 setValue 或 postValue 更新数据,然后在观察者,也就是 Activity 或 Fragment 中就获取更新数据了,如下:
public void setData(String data) {
mData.setValue(data);
}
那么如何创建没有 LifecycleOwner 的观察者呢? 可以使用 LiveData 对象的 observeForever 方法来将一个没有 LifecycleOwner 的类添加到观察者列表中,如下:
public class NoLifecycleOwner {
public void print(NViewModel viewModel, final TextView tvData){
//使用observeForever对象创建没有LifecycleOwner的观察者
viewModel.getData().observeForever(new Observer<String>() {
@Override
public void onChanged(String s) {
tvData.setText("我是没有LifecycleOwner的观察者:"+s);
}
});
}
}
自定义Livedata
/**
* 自定义LiveData
* Powered by jzman.
* Created on 2018/12/17 0017.
*/
public class CustomLiveData extends LiveData<String> {
@Override
protected void onActive() {
//有活跃观察者调用该方法
//开启服务...
}
@Override
protected void onInactive() {
//没有任何活跃观察者调用该方法
//结束服务...
}
}
LiveData转换
Lifecycle 提供了工具类 Transformations 来对 LiveData 的数据类型进行转换,可以在 LiveData 在数据返回给观察者之前修改 LiveData 中数据的具体类型,比如 int 型数字 1、2 等转化为中文大写壹、贰等,那么如何使用呢,创建 MapViewModel 如下:
public class MapViewModel extends ViewModel {
private MutableLiveData<Integer> mPrice = new MutableLiveData<>();
//Map
private LiveData<String> mMapPrice = Transformations.map(mPrice, new Function<Integer, String>() {
@Override
public String apply(Integer input) {
//返回String
return Util.getNumberCapital(input);
}
});
//SwitchMap
private LiveData<String> mSwitchMapPrice = Transformations.switchMap(mPrice, new Function<Integer, LiveData<String>>() {
@Override
public LiveData<String> apply(Integer input) {
//返回LiveData
MutableLiveData<String> data = new MutableLiveData<>();
data.postValue(Util.getNumberCapital(input));
return data;
}
});
public void setPrice(int price) {
mPrice.setValue(price);
}
public LiveData<String> getPrice() {
//Map
return mMapPrice;
//SwitchMap
// return mSwitchMapPrice;
}
}