且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Kotlin协程时Room dao类出现错误

更新时间:2023-01-12 11:37:38

您不能将suspend方法用于DAO. 在编译时处理挂起的函数,然后编译器更改此函数的签名(不同的返回类型,状态机回调的附加参数)以使其不阻塞.

You cannot use suspend methods for DAO. Suspend function processed in compile time and compiler changes the signature of this function (different return type, an additional argument for state machine callback) to make it non-blocking.

房间等待特定的方法签名生成代码.因此,除非Room不直接支持协程,否则您不能对DAO使用暂停功能.

Room waits for particular method signature to generate code. So, until Room doesn't support coroutines directly, you cannot use suspend function for DAO.

目前,您有以下解决方法:

For now, you have such workarounds:

  1. 如果DAO方法返回值,请使用RxJava或LiveData来获取它,并 使用用于RxJava的协程适配器,或为LiveData编写自己的适配器 (不知道现有的)
  2. 将同步DAO方法调用包装到 协程具有自己的线程池(因为这样的调用将被阻塞).
  1. If DAO method returns value, use RxJava or LiveData to get it and use coroutine adapter for RxJava or write your own for LiveData (don't know existing ones)
  2. Wrap synchronous DAO method call to coroutine with own thread pool (because such call will be blocking).

但是如果可能的话,请始终选择选项1,因为Room已经提供了非阻塞API,只需使用协程适配器即可将此API与协程一起使用而无需回调

But always prefer option 1 if it's possible because Room already provides non-blocking API, just use coroutine adapter to allow use this API with coroutines without callbacks

Room 2.1.0-alpha03开始,DAO方法现在可以是suspend函数.专门标记为@ Insert,@ Update或@Delete的Dao方法可以是挂起函数.尽管支持普通查询,但仍尚不支持.有关更多详细信息,请参见:建筑组件发行说明

As of Room 2.1.0-alpha03, DAO methods can now be suspend functions. Dao methods specifically annotated as @Insert, @Update, or @Delete can be suspend functions. Inserts, Updates, and Deletes annotated as @Query are not yet supported although normal queries are. For further details see: Architecture Components Release Notes and Feature Request.