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 getAll();

    @Query("SELECT * FROM user WHERE uid IN (:userIds)")
    List 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> getAccount();

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

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

    @Override
    protected List compute() {
      if (_observer == null) {
        _observer = new Observer("user_info") {
          @Override
          public void onInvalidated(@NonNull Set tables) {
            invalidate();
          }
        };
        __db.getInvalidationTracker().addWeakObserver(_observer);
      }
      final Cursor _cursor = __db.query(_statement);
      try {
        final int _cursorIndexOfUserId = _cursor.getColumnIndexOrThrow("user_id");
        ...
        final List _result = new ArrayList(_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() {
        @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,然后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 {

    // 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 loadFromDb();

    // Called to create the API call.
    // 创建网络数据请求
    @NonNull @MainThread
    protected abstract LiveData> 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> getAsLiveData();
}

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

NetworkBoundResource源码分析

public abstract class NetworkBoundResource {

    private final AppExecutors appExecutors;

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

    @MainThread
    public NetworkBoundResource(AppExecutors appExecutors) {
        this.appExecutors = appExecutors;
        LiveData 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 newValue) {
        if (!Objects.equals(result.getValue(), newValue)) {
            result.setValue(newValue);
        }
    }

    private void fetchFromNetwork(final LiveData dbSource) {
        LiveData> 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提供的架构的实现源码和设计思想

你可能感兴趣的:(livedata+room livedata踩坑之二)