Returning Single<Long> on @Insert in Android Room doesn't work

TUbuAsk :

So I need to get the ID of the inserted item back from the insert function. Multiple sources including this one from Google say that it is possible to do this via Single as return value of the @Insert annotated DAO function. Unfortunately compiling always exits with:

xxx\CarDao.java:19: error: Not sure how to handle insert method's return type. public abstract java.lang.Object insert(@org.jetbrains.annotations.NotNull()

I tried changing it to Maybe<Long>, Single<List<Long>> etc. but it's always the same error.

My code looks like this:

import androidx.lifecycle.LiveData
import androidx.room.*
import io.reactivex.Single


@Dao
interface CarDao {
    @Query("SELECT * FROM cars")
    fun getAll(): LiveData<List<Car>>

    @Query("SELECT * FROM cars WHERE uid = :uid")
    fun getById(uid: Int): Single<List<Car>>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(car: Car): Single<Long>>

    @Query("DELETE FROM cars WHERE uid = :uid")
    suspend fun deleteById(uid: Int)

}

I'm completely out of ideas of what is causing this. So what am I doing wrong and if it's just a bug, what would be a workaround to get the id in the context of my Activity and this activities data?

UPDATE: found a very strange solution: when I remove the suspend keyword it compiles without any problems. The problem then becomes the inability to access the database from main thread. Why does it work without suspend but not with suspend?

ianhanniballake :

You're using

suspend fun insert(car: Car): Single<Long>

Which is using both Coroutines (suspend) and Rx (Single). Room doesn't allow you to use both at once (nor does it make any sense since just one of them is enough) - you need to pick which async technique you want.

Therefore you can use Coroutines with:

suspend fun insert(car: Car): Long

Or Rx:

fun insert(car: Car): Single<Long>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=174160&siteId=1