0

I have an application that uses a Room database to store my "Friends" as accounts in an Account table

@Entity(tableName = "accounts")
data class Account(

    @PrimaryKey
    @ColumnInfo(name = "account_id")
    val accountId: Int,

    @ColumnInfo(name = "first_name", defaultValue = "")
    var firstname: String,

    @ColumnInfo(name = "last_name", defaultValue = "")
    var lastname: String,

    @ColumnInfo(name = "email", defaultValue = "")
    var email: String,

    @ColumnInfo(name = "status")
    var status: Int,

    @ColumnInfo(name = "role_id")
    var roleId: Int,

    @ColumnInfo(name = "lang", defaultValue = "")
    var lang: String

) : Serializable

So when i refresh my accounts, there might be accounts that

  1. will be deleted
  2. will be inserted
  3. will be updated

What is the most optimal way to identify what records need what action and how can i do it?

james04
  • 1,580
  • 2
  • 20
  • 46

1 Answers1

2

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.

sergiy tikhonov
  • 4,961
  • 1
  • 10
  • 27
  • please help, nobody help in this question https://stackoverflow.com/questions/66046272/i-can-auto-increment-id-in-room-database-but-when-refresh-database-its-shows-do – user10997009 Feb 05 '21 at 17:48