Search code examples
androidandroid-roomkotlin-flow

Not sure how to convert a Cursor to this method's return type in Room Android?


I am getting the following error when I build my application

Not sure how to convert a Cursor to this method's return type (kotlinx.coroutines.flow.Flow<? extends java.util.List<com.notification.NotificationEntity>>)

This is my Entity class

@Entity
internal data class NotificationEntity(
@PrimaryKey @ColumnInfo(name = "notification_id") val notificationId: String,
val title: String,
val body: String?,
@ColumnInfo(name = "is_actionable") val isActionable: Boolean,
@ColumnInfo(name = "created_at") val createdAt: Instant,
@ColumnInfo(name = "is_read") val isRead: Boolean = false)

And this is my Dao Class

@Dao
internal interface NotificationDao {

@Query("SELECT * FROM NotificationEntity ORDER BY created_at ASC")
suspend fun getAllNotifications(): Flow<List<NotificationEntity>>

@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun saveNotification(notifications: List<NotificationEntity>)
}

Can someone help what is the issue here?


Solution

  • When you declare Dao's function which returns Flow the function should not be suspendable. Please see docs.

    Change your code to:

    @Dao
    internal interface NotificationDao {
    
    @Query("SELECT * FROM NotificationEntity ORDER BY created_at ASC")
    fun getAllNotifications(): Flow<List<NotificationEntity>>
    
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun saveNotification(notifications: List<NotificationEntity>)
    }
    

    And add type converter for Instant type which used in NotificationEntity if not yet added.