LiveData use

### Andorid LiveData using
[[_TOC_]]
#### used Lifycycle
1, the interface inheritance FragmentActivity achieve LifecycleOwner
2, declare a LifecycleRegistry object corresponding to the Activity lifecycle status flag, and then the appropriate time by changing the lifecycle handleLifecycleEvent distribution corresponding event.
3, by passing LifecycleRegistry Activity of a target, to monitor the life cycle of the corresponding
* Example
`` `
public class LifycycleActivtiy the extends AppCompatActivity the implements LifecycleOwner {
LifecycleRegistry lifecycleRegistry;   
@Override   
protected void the onCreate (@Nullable the Bundle savedInstanceState) {super.onCreate (savedInstanceState );  
lifecycleRegistry = new new LifecycleRegistry (the 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
Data corresponding to the observed Activity life cycle, adding listeners LifecycleOwner by the Observer, when Activity is active, data mode notification by the observer is modified, also be added by observeForever (Observer) always describes the modification notification, but this ways need to manually invoke removeObserver (Observer).
Advantage: avoid memory leaks. The need to manually manage the life cycle of the observed data, data, the UI sync
common scenarios: When a network request returns, page has been destroy ()

Use:
1, the introduction of dependent packages
`` `
Implementation 'android.arch.lifecycle: Extensions: 1.1.1'
` ``
2, LiveData is an abstract class, have achieved its subclasses
MutableLiveData (single observation data).
MediatorLiveData: inherited MutableLiveData, observed for managing a plurality of data sources.
Often in combination ViewModel use.

3, first to achieve a the ViewModel
`` `
public class TestDataModel the extends the ViewModel {   
MutableLiveData <String> testData = new new MutableLiveData <> ();  
public MutableLiveData <String> getTestData, () { 
return testData;   
}}
` ``
viewing the on Activity data changes
`` `
ViewModelProviders.of (the this) .get (TestDataModel.class) .getTestData (). the observe (the this,
new new the Observer <String> () {   
@Override   
public void the onChanged (@Nullable String S) {   
LogUtil.e (S);   
}});
`
acquire the changed data source
`
@ threads on the running
ViewModelProviders.of (this) .get (TestDataModel.class) .getTestData () setValue ( "hello world. ");
on // postValue the main thread of 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);
}

`
By implementing Factory, Factory to the parameter passing, by the ViewModel Factory incoming
`

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

 

 

Guess you like

Origin www.cnblogs.com/changeMsBlog/p/11965562.html