### Andorid LiveData 使用
[[_TOC_]]
#### Lifycycle 使用
1、继承FragmentActivity 实现LifecycleOwner接口
2、声明一个LifecycleRegistry对象,用于标记Activity的相应声明周期状态,并再相应生命周期改变的时候通过handleLifecycleEvent分发相应的事件。
3、通过传递一个Activity的LifecycleRegistry 对象,来监听相应的生命周期变化
* 示例
```
public class LifycycleActivtiy extends AppCompatActivity implements LifecycleOwner {
LifecycleRegistry lifecycleRegistry;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState);
lifecycleRegistry=new LifecycleRegistry(this::getLifecycle);
lifecycleRegistry.markState(Lifecycle.State.CREATED);
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
getLifecycle().addObserver(new GenericLifecycleObserver() {
@Override
public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
LogUtil.e(event.toString());
}
});
}
@Override
protected void onStart() {
super.onStart(); l
ifecycleRegistry.markState(Lifecycle.State.STARTED);
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
}
@Override
protected void onResume() {
super.onResume();
lifecycleRegistry.markState(LifecycleRegistry.State.RESUMED);
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
}
@Override
protected void onStop() {
super.onStop();
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
}
@Override
protected void onDestroy() {
super.onDestroy();
lifecycleRegistry.markState(LifecycleRegistry.State.DESTROYED);
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
}
@Override
public Lifecycle getLifecycle() {
return lifecycleRegistry;
}}
```
#### LiveData
可以观察到数据对应的Activity生命周期,通过Observer 添加LifecycleOwner的监听,当Activity处于活动状态下,通过观察者模式通知数据被修改,同样也可以通过observeForever(Observer)添加始终介绍修改的通知,但是这种方式需要手动调用removeObserver(Observer)。
优势:避免内存泄漏。不需手动管理观察数据生命周期,数据、UI同步
常用场景:网络请求返回时,页面已经被destroy()
使用:
1、 引入相关依赖包
```
implementation 'android.arch.lifecycle:extensions:1.1.1'
```
2、LiveData 是一个抽象类,它的子类实现有
MutableLiveData(观察单个数据) 。
MediatorLiveData :继承于MutableLiveData,用于观察管理多个数据源。
常常结合ViewModel 使用。
3、首先实现一个ViewModel
```
public class TestDataModel extends ViewModel {
MutableLiveData<String> testData=new MutableLiveData<>();
public MutableLiveData<String> getTestData(){
return testData;
} }
```
在Activity上观察该数据变化
```
ViewModelProviders.of(this).get(TestDataModel.class).getTestData().observe(this,
new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
LogUtil.e(s);
}});
```
获取改变该数据源
```
//在该运行的线程上
ViewModelProviders.of(this).get(TestDataModel.class).getTestData().setValue("hello world");
//postValue 运行在this Activity 的主线程上
ViewModelProviders.of(this).get(TestDataModel.class).getTestData().postValue("hello world");
```
ViewModel 传递参数
通过**ViewModelProviders.of(FragmentActivity activity,Factory factory).get(Class<T> modelClass)** 实现参数传递
首先需要实现 **Factory** 接口
```
public interface Factory {
/** * Creates a new instance of the given {@code Class}. * <p> * * @param modelClass a {@code Class} whose instance is
requested * @param <T> The type parameter for the ViewModel. * @return a newly created ViewModel */
@NonNull
<T extends ViewModel> T create(@NonNull Class<T> modelClass);
}
```
通过实现Factory,往Factory中传参,在由Factory传入ViewModel
```
public class TestViewModel extends ViewModel {
private final String mValue;
private MutableLiveData<String> mValueEvent = new MutableLiveData<>();
public MutableLiveData<String> getNameEvent() {
return mNameEvent;
}
public TestViewModel(String value) {
mValue = value;
}
public static class Factory implements ViewModelProvider.Factory {
private String value;
public Factory(String str) {
value = str;
}
@Override
public <T extends ViewModel> T create(Class<T> modelClass) {
return (T) new TestViewModel(value);
}
}
public String getValue() {
return mValue;
}}
```
使用
```
ViewModelProviders.of(this, new TestViewModel.Factory(str)).get(TestViewModel.class)
```
示例代码:
https://github.com/RexKell/mvvmDemo