问题
I'm trying to use Coroutines with a Room database in an Android project. I've found almost no documentation online, and I'm wondering if it is possible to return Deferred<>
types in those methods. Something like this:
@Dao
interface MyObjectDAO {
@Query("SELECT * FROM myObject WHERE id_myObject = :idMyObject")
suspend fun readMyObjectAsync(idMyObject: Int): Deferred<MyObject>
}
I've tried this and I get Not sure how to convert a Cursor to this method's return type
at compile time.
My dependencies are:
kapt 'androidx.room:room-compiler:2.1.0-alpha04'
implementation 'androidx.room:room-runtime:2.1.0-alpha04'
implementation 'androidx.room:room-coroutines:2.1.0-alpha04'
回答1:
Your issue lies in that you're mixing the suspend
ing converter and the Deferred
converter. Use one or the other and your code will work as intended.
fun readMyObjectAsync(idMyObject: Int): Deferred<MyObject>
- Best choice if you need to interface/be compatible with java code, since it doesn't require code transformations to actually function.suspend fun readMyObjectAsync(idMyObject: Int): MyObject
- If you're operating on pure kotlin this will allow better control through the context it is called in.
来源:https://stackoverflow.com/questions/55925479/using-deferred-in-room-dao-with-kotlin-coroutines