Kotlin + Room + LiveData监听数据库数据变化

搞了一天终于搞出来了……一直不成功好像是因为 DB 对象没有写成单例。

Dao:

@Dao
interface ItemDao {
    @Query("SELECT * FROM item")
    fun getAll(): LiveData>

    @Query("SELECT * FROM item WHERE uid IN (:itemIds)")
    fun loadAllByIds(itemIds: IntArray): List

    @Insert
    fun insert(items: Item): Long

}

AppDatabase

@Database(entities = [Item::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun itemDao(): ItemDao
}

DBUtils

class DBUtils private constructor() {

    companion object {
        val instance: DBUtils by lazy { DBUtils() }

        private lateinit var context: Context
        private val database: AppDatabase by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
            Room.databaseBuilder(context, AppDatabase::class.java, "clipboard_manager.db").build()
        }

        fun getDatabase(context: Context): AppDatabase {
            this.context = context.applicationContext
            return database
        }
    }

}

使用

DBUtils.getDatabase(applicationContext).itemDao().getAll().observe(
    this, { items ->
        toast(items.toString())
    }
)

你可能感兴趣的:(Kotlin + Room + LiveData监听数据库数据变化)