Skip to content

Instantly share code, notes, and snippets.

@deskid
Created February 12, 2019 07:44
Show Gist options
  • Save deskid/403010b4c965213c1fd8122bf409d91f to your computer and use it in GitHub Desktop.
Save deskid/403010b4c965213c1fd8122bf409d91f to your computer and use it in GitHub Desktop.
Room and SQLite do not have any built-in methods to upsert a row, but you can add your own. You can make all of the Room Daos extend a BaseDao which can contain our upsert method insertOrUpdate.
@Dao
abstract class BaseDao<T> {
@Insert(onConflict = OnConflictStrategy.IGNORE)
abstract fun insert(obj: T): Long
@Insert(onConflict = OnConflictStrategy.IGNORE)
abstract fun insert(obj: List<T>): List<Long>
@Update
abstract fun update(obj: T)
@Update
abstract fun update(obj: List<T>)
@Transaction
open fun insertOrUpdate(obj: T) {
val id = insert(obj)
if (id == -1L) update(obj)
}
@Transaction
open fun insertOrUpdate(objList: List<T>) {
val insertResult = insert(objList)
val updateList = mutableListOf<T>()
for (i in insertResult.indices) {
if (insertResult[i] == -1L) updateList.add(objList[i])
}
if (!updateList.isEmpty()) update(updateList)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment