Room database.withTransaction { } block not Resolved

871 views Asked by At

I am following this tutorial about RemoteMediator and everything is fine until I run into a weird error when using database.withTransaction{} to allow database operations.

enter image description here

Unfortunately, the IDE doesn't seem (or is refusing) to recognize this very genuine and legit block. I have checked that I defined ROOM Database abstract class correctly and declared these ROOM and Paging 3 libs in build.gradle(app) file.

    // Room
    implementation "androidx.room:room-runtime:2.4.3"
    kapt "androidx.room:room-compiler:2.4.3"

    // Room-paging artifact
    implementation 'androidx.room:room-paging:2.4.3'

    // Paging 3.0
    implementation 'androidx.paging:paging-compose:1.0.0-alpha16'

So I decided to ignore the error and went ahead to call a dao function inside the withTransaction{} block but I get Suspension functions can be called only within a coroutine body.

This is a bit confusing since RemoteMediator's load() override function is already a suspend function.

Anyone with insights on this issue please help as I don't seem to be getting anywhere around this.

1

There are 1 answers

0
Tonnie On BEST ANSWER

Thanks to @ianhanniballake day-saving comment above, if you run into this situation just change the room-runtime flavor from:

implementation "androidx.room:room-runtime:2.4.3"
kapt "androidx.room:room-compiler:2.4.3"

to room-ktx flavor:

implementation "androidx.room:room-ktx:2.4.3"
kapt "androidx.room:room-compiler:2.4.3"

As per Developers Docs ktx-libs provide Kotlin Extensions and Coroutines support which is exactly what database.withTransaction{} block is - it is an extension function on RoomDatabase as shown on this line from the source code.

public suspend fun <R> RoomDatabase.withTransaction(block: suspend () -> R): R {

Android KTX is a set of Kotlin extensions that are included with Android Jetpack and other Android libraries. KTX extensions provide concise, idiomatic Kotlin to Jetpack, Android platform, and other APIs. To do so, these extensions leverage several Kotlin language features, including the following:

  • Extension functions
  • Extension properties
  • Lambdas
  • Named parameters
  • Parameter default values
  • Coroutines