LiveData使用


### 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

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM