Search code examples
kotlinandroid-room

Android ROOM - Kotlin - Insert return value with multiple parameters of different type


With Insert Room datbase, I need insert two entity at one time.

@Transaction
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insertChemicalChemistry(baseChemical: BaseChemical, langInfo: LanguageComplimentChemical?): List<Long>

I read the documentation on the android developer site text This is allowed

However, when my project build one exception throw in build output:

Not sure how to handle insert method's return type.

I try change the type return like Long, Map, other but not complete. I hope everyone can help me


Solution

  • What you could do is have something along the lines of:-

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun insert(baseChemical: BaseChemical): Long
    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun insert(langInfo: LanguageComplimentChemical): Long
    
    @Transaction
    @Query("")
    /*suspend*/ fun insertChemicalChemistry(baseChemical: BaseChemical, langInfo: LanguageComplimentChemical?): List<Long> {
        val rv1 = insert(baseChemical)
        var rv2: Long = -1
        if (langInfo != null) {
            rv2 = insert(langInfo)
        }
        return listOf(rv1,rv2)
    }
    

    This when you want to insert the pair of entities you would use insertChemicalChemistry

    • Note suspend removed for the demo
    • the @Query("") is used to fool Room into considering the function should be run within a transaction. Without, unless things have changed, the function would not be run within a transaction.

    You could also have the freedom to insert the entities individually using the respective insert function.

    Consider the following demo:-

        val bc = BaseChemical(null,"BC001","blah")
        val lc = LanguageComplimentChemical(name = "LC001", etc = "more blah")
    
        dao.insert(bc)
        dao.insert(lc)
        val result1 = dao.insertChemicalChemistry(bc,lc)
        val result2 = dao.insertChemicalChemistry(bc,null)
        val brkpnt = result1.get(0) + (result1.get(1) * 1024)
    
    • where the last line has a break point

    When run in debug mode then the result when the breakpoint is reached is:-

    enter image description here

    As can be seen:-

    • result1 has 2 values both of which are 2. That is, both the insert functions return the id field (as they are an alias of the rowid column) which is generated.
    • result2 has a value of 3 for the first value of the pair, the id of the BaseChemical and therefore it was inserted. However, the second value is -1, indicating that either a null LanguageComplimentChemical was passed (as was the case), or that the row was not inserted.
      • you could change var rv2: Long = -1 to use another value if you wanted to differentiate between an ignored insert and a null LanguageComplimentChemical.