Using Deferred<…> in Room DAO with Kotlin Coroutines

你。 提交于 2019-12-07 12:57:55

问题


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 suspending 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!