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

Android: Observing Room DB through LiveData & ViewModel in Activity

我创建了一个基本示例,其中 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 时没有抛出任何错误?

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

这是房间的默认行为。默认情况下,它将在后台线程上查询 return 类型为 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