Ahmad Sattout
Ahmad Sattout

Reputation: 2476

Room database observer

In Room database, I want to add some observer where the notifications are like: delete, insert, update.

I did kind of achieve that by creating an interface, and the adapter implement it. So each time one of the Database transactions is over, a matching operation is performed on the adapter.

But I'm not sure if this is the right way to do it, maybe rxjava has some way of doing it? Or maybe the DiffUtil in RecyclerView?

Upvotes: 0

Views: 5146

Answers (2)

Rajat Beck
Rajat Beck

Reputation: 1633

I suggest you to use Rxjava for it.

With the help of android.arch.persistence.room:rxjava2:1.1.1 in your dependency you can directly observe changes in your database.

Dao.kt

  @Query("SELECT * FROM table")
    abstract fun getAllData(): Flowable<List<TableData>>

Repository

fun getDataFromDb():Flowable<List<TableData>>= database.dao().getAllData()

ViewModel

repository.getDataFromDb()
.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeBy{
                        //Todo here you will receive the data whenever there is any change in database
                     }

Also point to note

Room only knows that the table has been modified but doesn’t know why and what has changed. Therefore, after the re-query, the result of the query is emitted by the LiveData or Flowable. Since Room doesn’t hold any data in memory and can’t assume that objects have equals(), it can’t tell whether this is the same data or not.You need to make sure that your DAO filters emissions and only reacts to distinct objects.

If the observable query is implemented using Flowables, use Flowable#distinctUntilChanged

   Flowable<TableData> = repository.getDataFromDb()
                          .distinctUntilChanged{previous,next-> //here you can check for difference }

you can follow this link for more detail

https://medium.com/androiddevelopers/7-pro-tips-for-room-fbadea4bfbd1

Upvotes: 5

Vishal Arora
Vishal Arora

Reputation: 2564

You should return LiveData objects from your Dao methods to observe CRUD operations.

LiveData will get updated when any CRUD operation is performed on your repo.

Then you can get updated data from your repo and reflect the changes in the adapter.

Upvotes: 0

Related Questions