0

Just starting to work with Kotlin flows. I basically only want to insert an item into a room database if the record is unique. I thought I could probably do this with @Insert(onConflict = OnConflictStrategy.REPLACE) but imageUrl will always be unique. I always need to check against plateText.

So far I've got this and I was looking for ways that I could optimize it.

override fun flowSaveSomeStuff(plateText: String, imageUrl: String): Flow<Boolean> {
    return db.infoDao().getItems().map { list ->
        list.none { it.plate == plateText }
    }.filter { it }.map {
        db.infoDao().insertItems(
            plateInfo(
                plateText,
                imageUrl
            )
        )
        true
    }
}

Any thoughts welcome.

aidanmack
  • 518
  • 1
  • 5
  • 16
  • You should add a unique constraint to your plateText and add OnConflictStrategy.IGNORE to not insert if the plateText already exist. – r6q Sep 21 '20 at 06:45

1 Answers1

0

Why don't you use if exists select 1 from (table name) where (id or imageUrl) = :(your parameter i.e imageUrl) Query it in function and return Boolean If it exists it will return true else false