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

标签 android android-room android-livedata android-viewmodel

我创建了一个基本示例,其中一个 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/

相关文章:

android - 如何在 flutter 上制作按钮

java - 从 mysql 数据库列接收到某些数据后,如何更改 recyclerview 中特定卡片的颜色

android - 刷新同一 Activity 中剩余的当前 fragment (ListView 数据)

android-fragments - 如何销毁使用 fragmentstateadapter (viewpager2) 创建的片段

java - 如何正确管理Android中的 Realm 以数据绑定(bind) View ,但关闭所有 Realm 实例?

java - SQLite Android 多选Args 一个选择参数

android - 如何使类型转换器与自定义类列表一起使用?

android - 使用 RXJava 监听 Room 数据库插入

java - Android Room - 处理对象中的对象列表和查询结果

android - 使用 LiveData 在 SeekBar 和 EditText 中取得进展