howlongtobeat-android/app/src/main/java/be/kuleuven/howlongtobeat/model/room/GameRepositoryRoomImpl.kt

40 lines
1.1 KiB
Kotlin
Raw Normal View History

2021-08-17 09:50:06 +02:00
package be.kuleuven.howlongtobeat.model.room
import android.content.Context
import androidx.room.Room
import be.kuleuven.howlongtobeat.model.Game
import be.kuleuven.howlongtobeat.model.GameRepository
2021-08-17 09:50:06 +02:00
class GameRepositoryRoomImpl(appContext: Context) :
GameRepository {
2021-08-17 09:50:06 +02:00
private val db: GameDatabase
private val dao: GameDao
2021-08-17 09:50:06 +02:00
init {
db = Room.databaseBuilder(appContext, GameDatabase::class.java, "todo-db")
2021-08-17 09:50:06 +02:00
.allowMainThreadQueries()
.build()
dao = db.todoDao()
}
override fun load(): List<Game> = dao.query()
override fun update(game: Game) = dao.update(listOf(game))
override fun find(id: Int): Game = load().single { it.id == id }
2021-08-17 09:50:06 +02:00
override fun save(game: Game) {
db.runInTransaction {
dao.insert(listOf(game))
}
}
override fun overwrite(items: List<Game>) {
2021-08-17 09:50:06 +02:00
// You'll learn more about transactions in the database course in the 3rd academic year.
db.runInTransaction {
dao.deleteAll()
dao.insert(items)
}
}
}