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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值