Refresh items in Room database

Let’s say you have new accounts:

val newList: List<Account> = ... //

You can place in Dao next methods:

// To delete all accounts that are not included in new list
@Query("DELETE FROM account WHERE accountId NOT IN (: newIds)")
suspend fun deleteOutdatedAccounts(newIds: List<Int>)

// To insert/update all accounts from the new list
// Thanks to OnConflictStrategy.REPLACE strategy you get both insert and update
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertUpdateAccounts(accounts: List<Account>)

// To do two methods above in single transaction
@Transaction
suspend fun refreshAccounts(newList List<Account>){
    deleteOutdatedAccounts(newList.map{it.accountId})
    insertUpdateAccounts(newList)    
}

Afterwards you can call method refreshAccounts(newList) from your repository or ViewModel/Presenter.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top