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'
Answer: a. You should not use them for any foreground task.
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.
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”.
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.
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With