Database with Room using Rxjava

Google发布了新的开源库Room,他是属于数据库层的,可以让我们顺畅的数据库,更多相关信息可以移步官方文档。
在这篇文章中,我们将使用更加优雅的方式来访问数据库,使用Rxjava来避免在UI线程中操作数据库,从而都移到后台线程中操作数据。
首先需要在build.gradle文件中引入如下的库:

// for room
compile "android.arch.persistence.room:runtime:1.0.0-beta1"
annotationProcessor "android.arch.persistence.room:compiler:1.0.0-beta1"

// for Rxjava
compile "io.reactivex.rxjava2:rxjava:2.0.6"
compile "io.reactivex.rxjava2:rxandroid:2.0.1"

首先创建实体类User作为示例,最近在学Kotlin,所以把所有的代码都改成了Kotlin,如有不正确之处,欢迎指正

@Entity(tableName = "users")
class User(@ColumnInfo(name = "first_name")
           var firstName: String?, @ColumnInfo(name = "last_name")
           var lastName: String?) {
    @PrimaryKey(autoGenerate = true)
    var uid: Int = 0
}

接着我们需要一个接口UserDao:

@Dao
interface UserDao {
    @Query("SELECT * FROM users")
    fun getAll(): Maybe>

    @Query("SELECT * FROM users WHERE uid IN (:userIds)")
    fun loadAllByIds(userIds: IntArray): Flowable>

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

    @Query("SELECT * FROM users where uid = :id")
    fun findById(id: Int): Maybe

    @Insert
    fun insertAll(vararg users: User)

    @Delete
    fun delete(user: User)

    @Update
    fun updateUsers(vararg users: User)
}

接着添加AppDatabase

@Database(entities = arrayOf(User::class), version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao
}

在我们的示例中,直接通过调用LocalCacheManager来访问数据库

class LocalCacheManager(private val context: Context) {
    private val db: AppDatabase

    init {
        db = Room.databaseBuilder(context, AppDatabase::class.java, DB_NAME).build()
    }

    val users: Maybe>
        get() = db.userDao().getAll()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())

    fun addUser(firstName: String, lastName: String): Completable {
        return Completable.fromAction {
            val user = User(firstName, lastName)
            db.userDao().insertAll(user)
        }.subscribeOn(Schedulers.io())
          .observeOn(AndroidSchedulers.mainThread())
    }

    fun deleteUser(user: User): Completable {
        return Completable.fromAction { db.userDao().delete(user) }.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
    }


    fun updateUser(user: User): Completable {
        user.firstName = "first name first name"
        user.lastName = "last name last name"
        return Completable.fromAction { db.userDao().updateUsers(user) }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
    }

    companion object {
        private val DB_NAME = "database-name"
        private var _instance: LocalCacheManager? = null

        fun getInstance(context: Context): LocalCacheManager {
            if (_instance == null) {
                _instance = LocalCacheManager(context)
            }
            return _instance as LocalCacheManager
        }
    }
}

原示例中使用的是接口回调的方式来通知数据操作完成的,我把这里都做了一些修改。
这样,所有的操作都移到了io线程中。

原文地址:https://medium.com/@alahammad/database-with-room-using-rxjava-764ee6124974

你可能感兴趣的:(Database with Room using Rxjava)