gpt4 book ai didi

Android:通过Activity中的LiveData和ViewModel观察Room DB

转载 作者:行者123 更新时间:2023-12-05 00:16:29 26 4
gpt4 key购买 nike

我创建了一个基本示例,其中一个 Activity 是通过 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)
})
}
}

所以,事情是这样的。它工作正常。后台对数据库的任何更新都会发生,然后 Activity 会收到回调。

但是,为什么在 MainThread 上访问(观察)DB 时没有抛出任何错误?

我是否以正确的方式实现?我错过了什么?

最佳答案

这是房间的默认行为。默认情况下,它将在后台线程上查询那些返回类型为 LiveData

的函数

Room generates all the necessary code to update the LiveData object when a database is updated. The generated code runs the query asynchronously on a background thread when needed. This pattern is useful for keeping the data displayed in a UI in sync with the data stored in a database.

More Info

关于Android:通过Activity中的LiveData和ViewModel观察Room DB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59946396/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com