Skip to content

Instantly share code, notes, and snippets.

@robertlevonyan
Last active March 18, 2021 06:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertlevonyan/e21b824cb2462a3c2b7db788884a478b to your computer and use it in GitHub Desktop.
Save robertlevonyan/e21b824cb2462a3c2b7db788884a478b to your computer and use it in GitHub Desktop.
class SqlDelightDao() {
/**
* Create a SqlDriver instance, which will maintain connections to an underlying SQL database and provide APIs
* for managing transactions and executing SQL statements.
* Params are a Schema of the generated database, an application context and a name of db
*/
private val driver: SqlDriver = AndroidSqliteDriver(Database.Schema, context, "caching.db")
// Instance of the generated database instance with adapter. Movie is a generated entoty
private val database = Database(driver, Movie.Adapter(DateAdapter()))
// Instance of generated MoviesQueries interface
private val queries = database.moviesQueries
override suspend fun save(movies: List<Movie>) {
movies.forEach { movie ->
queries.insert(movie) // insert is the label that was set to INSERT query in movies.sq file
}
}
override fun getMovies(): Flow<List<Movie>> =
queries.selectAll() // selectAll is the label that was set to SELECT query in movies.sq file
.asFlow() // convert to Coroutines Flow
.map { query ->
query.executeAsList().map { movie ->
Movie(
id = movie.id,
backdropPath = movie.backdropPath.orEmpty(),
posterPath = movie.posterPath.orEmpty(),
title = movie.title.orEmpty(),
overview = movie.overview.orEmpty(),
releaseDate = movie.releaseDate ?: Date(),
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment