Android - 架構組件學習(Android Architecture components)

開篇

對架構組件整體結構的學習:其中包含一個視頻,高度概括了Android Architecture compontens由哪幾部分構成,各個部分分別是什麼作用。

  • Room: 是一個強大的SQLite對象映射庫。
  • ViewModel:是一類對象,它用於爲UI組件提供數據,在設備配置發生變更時依舊可以存活。
  • LiveData: 是一個可感知生命週期、可被觀察的數據容器,它可以存儲數據,還會在數據發生改變時提醒你。
  • Lifecycle:包含LifeCycleOwerLifecycleObserver分別是生命週期所有者和生命週期感知者。

基礎

對生命週期組件的學習:給出了例子,並簡要介紹了LiveDataViewModel以及LifeCycle如何在項目中使用。

https://github.com/googlecodelabs/android-lifecycles

對數據庫組件的學習:給出了例子,簡單介紹了Room的設計理念,以及Dao/Query/Database/Entity/TypeConverters等註解的使用,也簡要介紹瞭如何同步查詢與異步LiveData查詢。

https://github.com/googlecodelabs/android-persistence

這其中涉及到一個比較有趣的工具類Transformations,其也做了簡要介紹:

  1. map:在LiveData存儲的value上應用一個函數apply,並將value的處理結果向下遊分發。
  2. 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);
        }
    });
}

建議

對架構組件學習的一些建議:翻譯在這裏

這篇文章主要從以下角度介紹了這些建議:

  1. View 和 ViewModels
  2. 臃腫的 ViewModels
  3. 使用數據倉庫
  4. 處理數據狀態
  5. 保存 Activity 狀態
  6. 事件
  7. 泄露 ViewModels
  8. 在倉庫中的 LiveData
  9. 繼承 LiveData
發佈了251 篇原創文章 · 獲贊 240 · 訪問量 71萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章