開篇
對架構組件整體結構的學習:其中包含一個視頻,高度概括了Android Architecture compontens
由哪幾部分構成,各個部分分別是什麼作用。
- Room: 是一個強大的SQLite對象映射庫。
- ViewModel:是一類對象,它用於爲UI組件提供數據,在設備配置發生變更時依舊可以存活。
- LiveData: 是一個可感知生命週期、可被觀察的數據容器,它可以存儲數據,還會在數據發生改變時提醒你。
- Lifecycle:包含
LifeCycleOwer
和LifecycleObserver
分別是生命週期所有者和生命週期感知者。
基礎
對生命週期組件的學習:給出了例子,並簡要介紹了LiveData
和ViewModel
以及LifeCycle
如何在項目中使用。
對數據庫組件的學習:給出了例子,簡單介紹了Room
的設計理念,以及Dao/Query/Database/Entity/TypeConverters
等註解的使用,也簡要介紹瞭如何同步查詢與異步LiveData
查詢。
這其中涉及到一個比較有趣的工具類Transformations
,其也做了簡要介紹:
map
:在LiveData
存儲的value
上應用一個函數apply
,並將value
的處理結果向下遊分發。switchMap
:很像map
函數,但是分發的結果被包裝了一層LiveData
,也就意味着我們可以根據初始的LiveData
的觀察結果再觸發一次其他可以被觀察的操作。
Transformations
This step uses a class called Transformations that includes two very valuable functions:
map: Applies a function on the LiveData value and dispatches the result downstream.
switchMap: Similar to map, but dispatches a result wrapped in LiveData.
They are very useful for cases where you need to transform data before exposing it or when data might not be always ready.
map的例子,對查詢的結果進行轉換:
mLoansResult = Transformations.map(loans, new Function<List<LoanWithUserAndBook>, String>() {
@Override
public String apply(List<LoanWithUserAndBook> loansWithUserAndBook) {
StringBuilder sb = new StringBuilder();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm",
Locale.US);
for (LoanWithUserAndBook loan : loansWithUserAndBook) {
sb.append(String.format("%s\n (Returned: %s)\n",
loan.bookTitle,
simpleDateFormat.format(loan.endTime)));
}
return sb.toString();
}
});
switchMap的例子,根據查詢的結果再觸發一次查詢:
protected LiveData<List<Repo>> loadFromDb() {
return Transformations.switchMap(repoDao.search(query), searchData -> {
if (searchData == null) {
return AbsentLiveData.create();
} else {
return repoDao.loadOrdered(searchData.repoIds);
}
});
}
建議
對架構組件學習的一些建議:翻譯在這裏。
這篇文章主要從以下角度介紹了這些建議:
- View 和 ViewModels
- 臃腫的 ViewModels
- 使用數據倉庫
- 處理數據狀態
- 保存 Activity 狀態
- 事件
- 泄露 ViewModels
- 在倉庫中的 LiveData
- 繼承 LiveData