Created
February 12, 2019 07:44
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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