Last active
March 18, 2021 06:36
-
-
Save robertlevonyan/e21b824cb2462a3c2b7db788884a478b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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