Insert Or Update with Android Room

Skele·2024년 6월 25일
0

Android

목록 보기
13/15

Scenario

  1. Insert data into the table if it doesn't exist.
  2. If it exists, update the data in the table.

Just like in any database, It can be done using transaction with INSERT OR IGNORE followed by UPDATE.
One thing different is using @Insert with onConflict option instead of plain query.

@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insertOrIgnoreTask(task: Task) : Long

@Update
suspend fun updateTask(task: Task)

@Transaction
suspend fun insertOrUpdateTask(task: Task){
    val row = insertOrIgnoreTask(task)
    if(row < 0) updateTask(task)
}
profile
Tireless And Restless Debugging In Source : TARDIS

0개의 댓글