Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Deferred<...> in Room DAO with Kotlin Coroutines

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'
like image 292
bernardo.g Avatar asked Apr 30 '19 16:04

bernardo.g


People also ask

When should you not use coroutines?

Answer: a. You should not use them for any foreground task.

Can coroutines in Kotlin be suspended and resumed mid execution?

Coroutines can suspend themselves, and the dispatcher is responsible for resuming them. To specify where the coroutines should run, Kotlin provides three dispatchers that you can use: Dispatchers. Main - Use this dispatcher to run a coroutine on the main Android thread.

Why Kotlin coroutines are lightweight?

This works because coroutines can be suspended at suspension points and then resumed at a later point in time. 🧱 Coroutines allow you to achieve concurrent behavior without switching threads, which results in more efficient code. Therefore, coroutines are often called “lightweight threads”.

How coroutines work under the hood?

Coroutines simplify asynchronous operations on Android. As explained in the documentation, we can use them to manage asynchronous tasks that might otherwise block the main thread and cause your app to freeze. In the coroutines code, we added the suspend modifier to the function.


1 Answers

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.
like image 98
Kiskae Avatar answered Nov 10 '22 21:11

Kiskae