Search code examples
androidandroid-roomandroid-livedataandroid-viewmodel

Android: Observing Room DB through LiveData & ViewModel in Activity


I have created a basic example in which, an activity is observing room DB through LiveData. For more information, please check the following code:

    @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)
            })
        }
    }

So, here is the thing. It is working fine. Any update on DB from the background happens then Activity gets a callback.

However, Why is it not throwing any error while accessing (observing) DB on MainThread?

Did I implement in the correct way? What am I missing in this?


Solution

  • It is the default behavior of the Room. By default, it will query on the background thread for those functions whose return-type is 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