Uma*_*ari 2 android android-room android-livedata android-viewmodel
我创建了一个基本示例,其中的活动是通过 LiveData 观察房间数据库。欲了解更多信息,请查看以下代码:
@Dao
interface NoteDao {
@Query("SELECT * FROM note ORDER BY date_created DESC")
fun getAll(): LiveData<List<Note>>
}
// Repository
class ReadersRepository(private val context: Context) {
private val appDatabase = Room.databaseBuilder(context, AppDatabase::class.java, DATABASE_NAME)
.build()
fun getAllNotes(): LiveData<List<Note>> {
return appDatabase.getNoteDao().getAll()
}
}
// ViewModel
class AllNotesViewModel(application: Application) : AndroidViewModel(application) {
private val repository = ReadersRepository(application)
internal var allNotesLiveData: LiveData<List<Note>> = repository.getAllNotes()
}
// Activity
class MainActivity : BaseActivity<AllNotesViewModel>() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
viewModel.allNotesLiveData.observe(this, Observer {
adapter.setData(it)
})
}
}
Run Code Online (Sandbox Code Playgroud)
所以,事情就是这样。它运行良好。后台对数据库的任何更新都会发生,然后 Activity 会收到回调。
但是,为什么在主线程上访问(观察)数据库时没有抛出任何错误?
我是否以正确的方式实施?我在这方面缺少什么?