Android Room Persistence Library: Upsert

前端 未结 9 613
太阳男子
太阳男子 2020-12-12 10:50

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

9条回答
  •  离开以前
    2020-12-12 11:42

    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)
        }
    }
    

提交回复
热议问题