什麼是LiveData
LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state. Source:developer.android.com/topic/libra…
什麼是ViewModel
The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations. Source:developer.android.com/topic/libra…
ViewModel的生命週期
寫個Demo
引入依賴庫
implementation "android.arch.lifecycle:extensions:1.1.1"
extensions庫中包含的內容如下:
整體架構
步驟
建立Model,定義資料結構
public class MainBean {
public DataBean data;
public static class DataBean {
public String name;
}
}
複製程式碼
建立Repository,獲取資料並暴露介面給ViewModel
public MutableLiveData<MainBean> getData(int id) {
//構造需要暴露的資料結構
final MutableLiveData<MainBean> liveData = new MutableLiveData<>();
//獲取資料
MainApiService mainApiService = retrofit.create(MainApiService.class);
Call<MainBean> call = mainApiService.getData(id);
call.enqueue(new Callback<MainBean>() {
@Override
public void onResponse(Call<MainBean> call, Response<MainBean> response) {
//設定資料
if (response.isSuccessful()) {
liveData.setValue(response.body());
} else {
liveData.setValue(null);
}
}
@Override
public void onFailure(Call<MainBean> call, Throwable t) {
liveData.setValue(null);
}
});
//返回資料
return liveData;
}
複製程式碼
建立ViewModel,編寫View層真正需要的介面
如果View層需要直接操作MainBean,可以這樣處理:
public LiveData<MainBean> getData() {
return mainRepository.getData();
}
複製程式碼
如果View層只需要name欄位,用於顯示名字,可以這樣處理:
public LiveData<String> getData() {
int id = 1;
final MutableLiveData<MainBean> liveData = mainRepository.getData(id);
//執行資料轉換操作並獲得轉換後的資料
LiveData<String> newLiveData = Transformations.switchMap(liveData, new Function<MainBean, LiveData<String>>() {
@Override
public LiveData<String> apply(MainBean mainBean) {
final MutableLiveData<String> newLiveData = new MutableLiveData<>();
if (mainBean == null || mainBean.data == null) {
newLiveData.setValue(null);
} else {
newLiveData.setValue(mainBean.data.name);
}
return newLiveData;
}
});
//返回轉換後的資料
return newLiveData;
}
複製程式碼
建立View層,僅執行UI顯示邏輯,不可執行資料處理邏輯
mainViewModel.getData().observe(this, new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
mainFragmentText.setText(s);
}
});
複製程式碼
完整程式碼,請看Github
什麼是LifeCycle
上面的LiveData元件的核心實際上就是Lifecycle,比如我們想要監聽Acitivity等元件的生命週期,就可以使用該類實現,下面介紹一下如何使用:
首先使Activity等元件實現LifecycleRegistryOwner(這個類實際上已經過時了,但是我仍實現他是因為實現LifecycleOwner在Fragment中會出現無法監聽生命週期的問題)
public class LifecycleActivity extends FragmentActivity implements LifecycleRegistryOwner {
private LifecycleRegistry lifecycleRegistry = new LifecycleRegistry(this);
@NonNull
@Override
public LifecycleRegistry getLifecycle() {
return lifecycleRegistry;
}
}
複製程式碼
建立LifecycleObserver類,監聽生命週期變化
public class ActivityLifecycleObserver implements LifecycleObserver {
private static final String TAG = "ActivityObserver";
private Context context;
public ActivityLifecycleObserver(Context context) {
this.context = context;
}
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreate() {
Log.d(TAG, "onCreate");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart() {
Log.d(TAG, "onStart");
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume() {
Log.d(TAG, "onResume");
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause() {
Log.d(TAG, "onPause");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStop() {
Log.d(TAG, "onStop");
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy() {
Log.d(TAG, "onDestroy");
}
//任意回撥都會呼叫它,比如呼叫完onCreate()後會回撥這裡的onCreate(),然後會回撥onAny();
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
public void onAny() {
Log.d(TAG, "onAny");
}
}
複製程式碼
註冊
getLifecycle().addObserver(new ActivityLifecycleObserver(getApplicationContext()));
複製程式碼
LifeCycle目前只寫到這裡,還沒有繼續深入,繼續努力中...