Android\'s Room persistence library graciously includes the @Insert and @Update annotations that work for objects or collections. I however have a use case (push notificatio
If you have legacy code: some entities in Java and BaseDao as Interface
(where you cannot add a function body) or you too lazy for replacing all implements
with extends
for Java-children.
Note: It works only in Kotlin code. I'm sure that you write new code in Kotlin, I'm right? :)
Finally a lazy solution is to add two Kotlin Extension functions
:
fun BaseDao.upsert(entityItem: T) {
if (insert(entityItem) == -1L) {
update(entityItem)
}
}
fun BaseDao.upsert(entityItems: List) {
val insertResults = insert(entityItems)
val itemsToUpdate = arrayListOf()
insertResults.forEachIndexed { index, result ->
if (result == -1L) {
itemsToUpdate.add(entityItems[index])
}
}
if (itemsToUpdate.isNotEmpty()) {
update(itemsToUpdate)
}
}