Search code examples
androidkotlinandroid-roomkotlin-flow

Android Observable Queries not working after adding suspend word


I am trying to migrate from LiveData to Kotlin Flow. Right now I am working on a project that has offline supports in Room.

I was looking through the documentation and I managed to write an observable query in coroutines with Flow. (see: here)

The problem that I am facing right now is that whenever I add the suspend keyword inside the DAO class and try to run the project, it fails with the following error:

error: Not sure how to convert a Cursor to this method's return type (kotlinx.coroutines.flow.Flow<MyModel>).

The code with the problem:

@Transaction
@Query("SELECT * FROM table WHERE status = :status LIMIT 1")
suspend fun getWithSpecificStatus(status: String): Flow<MyModel?>

I am calling the code like this:

val modelLiveData: LiveData<MyModel?> = liveData(Dispatchers.IO) {
        val result = databaseService.getWithSpecificStatus(Enum.IN_PROGRESS.status).first()

        result?.let {
            emit(it)
        }

    }

I tried to keep things simple. why is my code failing?


Solution

  • You could directly initialise the value of modelLiveData as:

        val modelLiveData=databaseService.
        getWithSpecificStatus(Enum.IN_PROGRESS.status).first()
        .asLiveData()
    

    You have used Flow so asLiveData() is used to convert it to LiveData

    Also suggestion , you do should not use the suspend keyword because when you are returning Flow, Room automatically does this asynchronously. You just need to consume the Flow.