开篇
对架构组件整体结构的学习:其中包含一个视频,高度概括了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