Skip to content

Instantly share code, notes, and snippets.

@robertlevonyan
Created March 4, 2021 07:14
Show Gist options
  • Save robertlevonyan/fb8926578e9ea6d3a27d6db4c1490d73 to your computer and use it in GitHub Desktop.
Save robertlevonyan/fb8926578e9ea6d3a27d6db4c1490d73 to your computer and use it in GitHub Desktop.
class RealmDao() {
private val realm: Realm = Realm.getDefaultInstance()
suspend fun save(movies: List<Movie>) {
realm.executeTransactionAwait { r -> // open a realm transaction
for (movie in movies) {
if (r.where(RealmMovie::class.java).equalTo("id", movie.id).findFirst() != null) {
continue
}
val realmMovie = r.createObject(RealmMovie::class.java, movie.id) // create object (table)
// save data
realmMovie.backdropPath = movie.backdropPath
realmMovie.posterPath = movie.posterPath
realmMovie.title = movie.title
realmMovie.overview = movie.overview
realmMovie.releaseDate = movie.releaseDate
}
}
}
fun getMovies(): Flow<List<Movie>> = callbackFlow { // wrap result in callback flow
realm.executeTransactionAwait { r ->
val movies = r.where(RealmMovie::class.java).findAll() // get movies from Realm db
offer(movies.map { it.toMovie() }) // toMovie() is a mapper extension
}
awaitClose { println("End Realm") }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment