livedata+room livedata踩坑之二

前言

前面我们说过了livedata的使用; livedata是一个数据源;当其有active的observer时会通知其观察者;livedata提供的数据可能来自于网络;也可能来自于数据库; 而jetpack为数据库也提供了封装的工具;也就是room

这样就能把我们的项目设计为


jetpack常用架构.png

首先我们看下room的相关介绍

room介绍

参考: https://developer.android.com/training/data-storage/room/index.html

room的构成

Database: Contains the database holder and serves as the main access point for the underlying connection to your app's persisted, relational data.
The class that's annotated with @Database should satisfy the following conditions:
Be an abstract class that extends RoomDatabase.
Include the list of entities associated with the database within the annotation.
Contain an abstract method that has 0 arguments and returns the class that is annotated with @Dao.
At runtime, you can acquire an instance of Database by calling Room.databaseBuilder() orRoom.inMemoryDatabaseBuilder().
Entity: Represents a table within the database.
DAO: Contains the methods used for accessing the database.
可以看到,

DAO(Data Access Object) 数据访问对象是一个面向对象的数据库接口 (提供用来操作数据库中相关表的接口)

Entity 代表数据库中的表
The app uses the Room database to get the data access objects, or DAOs, associated with that database. The app then uses each DAO to get entities from the database and save any changes to those entities back to the database. Finally, the app uses an entity to get and set values that correspond to table columns within the database.


room_architecture.png

room使用示例:

Entity

@Entity
public class User {
    @PrimaryKey
    public int uid;

    @ColumnInfo(name = "first_name")
    public String firstName;

    @ColumnInfo(name = "last_name")
    public String lastName;
}

UserDao

@Dao
public interface UserDao {
    @Query("SELECT * FROM user")
    List<User> getAll();

    @Query("SELECT * FROM user WHERE uid IN (:userIds)")
    List<User> loadAllByIds(int[] userIds);

    @Query("SELECT * FROM user WHERE first_name LIKE :first AND " +
           "last_name LIKE :last LIMIT 1")
    User findByName(String first, String last);

    @Insert
    void insertAll(User... users);

    @Delete
    void delete(User user);
}

AppDatabase

@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
    public abstract UserDao userDao();
}

After creating the files above, you get an instance of the created database using the following code:

AppDatabase db = Room.databaseBuilder(getApplicationContext(),
        AppDatabase.class, "database-name").build();

注意

If your app runs in a single process, you should follow the singleton design pattern when instantiating an AppDatabaseobject. Each RoomDatabase instance is fairly expensive, and you rarely need access to multiple instances within a single process.

也就说我们应该尽可能少的创建database对象,因为这个消耗是很大的;尽量多张DAO和表放在一个database中

room和livedata的结合使用

我们经常将room和livedata结合使用; 类似Dao中的接口如下:

LiveData<List<UserInfoData>> getAccount();

编译后会生成一个Dao_Impl,这里面是Dao接口真正的实现

@Override
public LiveData<List<UserInfoData>> getAccount() {
  final String _sql = "select * from user_info order by login_time desc";
  final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 0);
  return new ComputableLiveData<List<UserInfoData>>() {
    private Observer _observer;

    @Override
    protected List<UserInfoData> compute() {
      if (_observer == null) {
        _observer = new Observer("user_info") {
          @Override
          public void onInvalidated(@NonNull Set<String> tables) {
            invalidate();
          }
        };
        __db.getInvalidationTracker().addWeakObserver(_observer);
      }
      final Cursor _cursor = __db.query(_statement);
      try {
        final int _cursorIndexOfUserId = _cursor.getColumnIndexOrThrow("user_id");
        ...
        final List<UserInfoData> _result = new ArrayList<UserInfoData>(_cursor.getCount());
        while(_cursor.moveToNext()) {
          final UserInfoData _item;
          _item = new UserInfoData();
          _item.userId = _cursor.getLong(_cursorIndexOfUserId);
          _item.nickname = _cursor.getString(_cursorIndexOfNickname);
          _item.avatarUrl = _cursor.getString(_cursorIndexOfAvatarUrl);
          _item.token = _cursor.getString(_cursorIndexOfToken);
          final int _tmp;
          _tmp = _cursor.getInt(_cursorIndexOfIsVerified);
          _item.isVerified = _tmp != 0;
          _item.userType = _cursor.getInt(_cursorIndexOfUserType);
          final int _tmp_1;
          _tmp_1 = _cursor.getInt(_cursorIndexOfIsPay);
          _item.isPay = _tmp_1 != 0;
          final int _tmp_2;
          _tmp_2 = _cursor.getInt(_cursorIndexOfIsBound);
          _item.isBound = _tmp_2 != 0;
          _item.loginTime = _cursor.getLong(_cursorIndexOfLoginTime);
          final int _tmp_3;
          _tmp_3 = _cursor.getInt(_cursorIndexOfHasPwd);
          _item.hasPwd = _tmp_3 != 0;
          _item.mobile = _cursor.getString(_cursorIndexOfMobile);
          _item.sdkOpenId = _cursor.getString(_cursorIndexOfSdkOpenId);
          _item.ttUserId = _cursor.getLong(_cursorIndexOfTtUserId);
          _result.add(_item);
        }
        return _result;
      } finally {
        _cursor.close();
      }
    }

可以看到返回的是一个ComputableLiveData,其中实现了compute方法

ComputableLiveData源码分析

/**
 * Creates a computable live data that computes values on the arch IO thread executor.
 */
@SuppressWarnings("WeakerAccess")
public ComputableLiveData() {
    this(ArchTaskExecutor.getIOThreadExecutor());
}

/**
 *
 * Creates a computable live data that computes values on the specified executor.
 *
 * @param executor Executor that is used to compute new LiveData values.
 */
@SuppressWarnings("WeakerAccess")
public ComputableLiveData(@NonNull Executor executor) {
    mExecutor = executor;
    mLiveData = new LiveData<T>() {
        @Override
        protected void onActive() {
            mExecutor.execute(mRefreshRunnable);
        }
    };
}

可以看到mExecutor持有的是一个 IO thread executor; 同时可以创建一个livedata;当有active的observer监听它时,会通过子线程执行mRefreshRunnable

@VisibleForTesting
final Runnable mRefreshRunnable = new Runnable() {
    @WorkerThread
    @Override
    public void run() {
        boolean computed;
        do {
            computed = false;
            // compute can happen only in 1 thread but no reason to lock others.
            if (mComputing.compareAndSet(false, true)) {
                // as long as it is invalid, keep computing.
                try {
                    T value = null;
                    while (mInvalid.compareAndSet(true, false)) {
                        computed = true;
                        value = compute();
                    }
                    if (computed) {
                        mLiveData.postValue(value);
                    }
                } finally {
                    // release compute lock
                    mComputing.set(false);
                }
            }
            // check invalid after releasing compute lock to avoid the following scenario.
            // Thread A runs compute()
            // Thread A checks invalid, it is false
            // Main thread sets invalid to true
            // Thread B runs, fails to acquire compute lock and skips
            // Thread A releases compute lock
            // We've left invalid in set state. The check below recovers.
        } while (computed && mInvalid.get());
    }
};
private AtomicBoolean mInvalid = new AtomicBoolean(true);
private AtomicBoolean mComputing = new AtomicBoolean(false);

那么就可以看到会调用compute计算出数据,然后再通过setValue来触发active observer的处理; compute计算出数据库里的List<UserInfoData>,然后setValue来触发其观察者的onchanged函数;

那么这样就可能也会出现多次处理的问题; 比如fragment跳转没有销毁livedata,那么重新返回时observer也重新重新active,那么就会触发一次onchanged的处理;

但是如果有监听了ComputableLiveData的observer;从上面的分析中也会触发一次setValue,那么会找到所有的lobserver,再调用一次onchanged函数,造成重复;

我们的处理是用上一篇文章中的TransformationsForSingleLiveEvent和MediatorSingleLiveEvent进行收口和规范,这样不管是多个observer还是一个observer触发多次;只要setValue不会再次调用,那么只会触发一次;不过这个还是要根据具体的业务场景啊,不应该生搬硬套;

这里只是分析下room和livedata结合的原理以及可能出现的问题

NetworkBoundResource
前面说到livedata的数据源可以由网络提供,也可以由数据库提供;但是一定要注意,需要满足Single Source of Truth(单一数据源)原则; google我们提供了NetworkBoundResource用来保证fetch Network和room数据库的单一数据源原则

参考 https://developer.android.com/jetpack/docs/guide#addendum

NetworkBoundResource的作用:显示数据库缓存的同时可以加载网络数据,并将其结果更新到数据库中,再由数据库分发到UI层。
NetworkBoundResource的设计意图:在单一数据源原则下设计的数据加载帮助类(数据库/网络)。

NetworkBoundResource的使用

// ResultType: Type for the Resource data
// RequestType: Type for the API response
public abstract class NetworkBoundResource<ResultType, RequestType> {

    // Called to save the result of the API response into the database
    // 当要把网络数据存储到数据库中时调用
    @WorkerThread
    protected abstract void saveCallResult(@NonNull RequestType item);

    // Called with the data in the database to decide whether it should be
    // fetched from the network.
    // 决定是否去网络获取数据
    @MainThread
    protected abstract boolean shouldFetch(@Nullable ResultType data);

    // Called to get the cached data from the database
    // 用于从数据库中获取缓存数据
    @NonNull @MainThread
    protected abstract LiveData<ResultType> loadFromDb();

    // Called to create the API call.
    // 创建网络数据请求
    @NonNull @MainThread
    protected abstract LiveData<ApiResponse<RequestType>> createCall();

    // Called when the fetch fails. The child class may want to reset components
    // like rate limiter.
    // 网络数据获取失败时调用
    @MainThread
    protected void onFetchFailed() {
    }

    // returns a LiveData that represents the resource, implemented
    // in the base class.
    public final LiveData<Resource<ResultType>> getAsLiveData();
}

接口如下,我们通过实现接口,可以达到从网络或者数据库中来得到数据,并将得到的数据组织成livedata的形式; 从我看的结果,一般好多人会单独实现网络的部分或者数据库取数据的部分;但实际上其功能远不止如此; 我们会在下一节中进行分析

NetworkBoundResource源码分析

public abstract class NetworkBoundResource<ResultType, RequestType> {

    private final AppExecutors appExecutors;

    private final MediatorLiveData<Resource<ResultType>> result = new MediatorLiveData<>();

    @MainThread
    public NetworkBoundResource(AppExecutors appExecutors) {
        this.appExecutors = appExecutors;
        LiveData<ResultType> dbSource = loadFromDb();
        result.addSource(dbSource, data -> {
            result.removeSource(dbSource);
            if (shouldFetch(data)) {
                fetchFromNetwork(dbSource);
            } else {
                result.addSource(dbSource, newData -> setValue(Resource.success(newData)));
            }
        });
    }

    @MainThread
    private void setValue(Resource<ResultType> newValue) {
        if (!Objects.equals(result.getValue(), newValue)) {
            result.setValue(newValue);
        }
    }

    private void fetchFromNetwork(final LiveData<ResultType> dbSource) {
        LiveData<ApiResponse<RequestType>> apiResponse = createCall();
        // we re-attach dbSource as a new source, it will dispatch its latest value quickly
        result.addSource(dbSource, newData -> setValue(Resource.loading(newData)));
        result.addSource(apiResponse, response -> {
            result.removeSource(apiResponse);
            result.removeSource(dbSource);
            //noinspection ConstantConditions
            if (response.isSuccessful()) {
                appExecutors.diskIO().execute(() -> {
                    saveCallResult(processResponse(response));
                    appExecutors.mainThread().execute(() ->
                            // we specially request a new live data,
                            // otherwise we will get immediately last cached value,
                            // which may not be updated with latest results received from network.
                            result.addSource(loadFromDb(),
                                    newData -> setValue(Resource.success(newData)))
                    );
                });
            } else {
                onFetchFailed();
                result.addSource(dbSource,
                        newData -> setValue(Resource.error(response.errorMessage, newData)));
            }
        });
    }

可以看到还是通过MediatorLiveData来进行实现,添加不同的数据源; 那么如何保证单一数据源的呢?
关键在

 result.addSource(apiResponse, response -> {
            result.removeSource(apiResponse);
            result.removeSource(dbSource);
            //noinspection ConstantConditions
            if (response.isSuccessful()) {
                appExecutors.diskIO().execute(() -> {
                    saveCallResult(processResponse(response));
                    appExecutors.mainThread().execute(() ->
                            // we specially request a new live data,
                            // otherwise we will get immediately last cached value,
                            // which may not be updated with latest results received from network.
                            result.addSource(loadFromDb(),
                                    newData -> setValue(Resource.success(newData)))
                    );
                });

可以看到从网络中取到数据之后,将其存到数据库中,再监听数据的变化,从而对外提供数据源;这样就能保证livadata的数据提供者还是数据库;

network-bound-resource.png

这样实现了一边从网络拉数据,一边向数据库进行书写; 同时数据库中的数据变化触发对外的observer的变化,保证了单一数据源的原则;比较巧妙的写法

总结

Android jetpack给我们提供了很方便的数据处理,view更新的方式;并从数据的保存,通知view数据变化都有很方便的架构帮助我们实现;但是如果对框架的实现不够熟悉,会出现很多意想不到的错误,这里只是记录项目中遇到的一些坑,顺便从中学习下jetpack提供的架构的实现源码和设计思想

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,393评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,790评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,391评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,703评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,613评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,003评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,507评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,158评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,300评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,256评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,274评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,984评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,569评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,662评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,899评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,268评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,840评论 2 339