使用 ROOM 数据库作为单一数据源,配合 LiveData 在 MVVM 模式中实现数据的访问、操作和展示。
示例代码如下:
@Entity(tableName = "user") data class User( @PrimaryKey val userId: Long, val userName: String )
@Dao
interface UserDao {
@Query("SELECT * FROM user")
fun getAll(): LiveData>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(user: User)
@Delete
suspend fun delete(user: User)
}
@Database(entities = [User::class], version = 1) abstract class AppDatabase : RoomDatabase() { abstract fun userDao(): UserDao
companion object {
@Volatile
private var INSTANCE: AppDatabase? = null
fun getDatabase(context: Context): AppDatabase {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java,
"app_database"
).build()
INSTANCE = instance
instance
}
}
}
}
class MainViewModel(application: Application) : AndroidViewModel(application) {
private val userDao = AppDatabase.getDatabase(application).userDao()
val users = userDao.getAll()
fun insert(user: User) = viewModelScope.launch {
userDao.insert(user)
}
fun delete(user: User) = viewModelScope.launch {
userDao.delete(user)
}
}
viewModel.users.observe(viewLifecycleOwner, { userList -> // 更新 UI })