Error with Room dao class when using Kotlin coroutines

前端 未结 2 647
夕颜
夕颜 2020-12-30 12:51

I\'m trying to use kotlin coroutines to access room database by the method described here, added the plugin and dependency, and enabled kotlin coroutines in gradle.

相关标签:
2条回答
  • 2020-12-30 13:13

    actually it is possible,

    you need to use:

    implementation "androidx.room:room-coroutines:${versions.room}"
    

    you can follow this tutorial: https://medium.com/androiddevelopers/room-coroutines-422b786dc4c5

    Additionally, the version that worked for me was: 2.1.0-alpha04 So, my Room deps was exactly:

    implementation "androidx.room:room-runtime:2.1.0-alpha04"
    implementation "androidx.room:room-coroutines:2.1.0-alpha04"
    kapt "androidx.room:room-compiler:2.1.0-alpha04"
    
    0 讨论(0)
  • 2020-12-30 13:24

    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 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. 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).

    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

    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.

    0 讨论(0)
提交回复
热议问题